0% found this document useful (0 votes)
17 views129 pages

C Introductory

The document provides an overview of programming concepts including syntax, source code, machine code, compilers, and the terminal interface. It explains the importance of preprocessor directives, libraries, functions, keywords, variables, constants, data types, operators, type casting, and comments in C programming. Additionally, it covers input/output functions like printf and scanf, along with placeholders and escape sequences.

Uploaded by

sardarsaifali629
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views129 pages

C Introductory

The document provides an overview of programming concepts including syntax, source code, machine code, compilers, and the terminal interface. It explains the importance of preprocessor directives, libraries, functions, keywords, variables, constants, data types, operators, type casting, and comments in C programming. Additionally, it covers input/output functions like printf and scanf, along with placeholders and escape sequences.

Uploaded by

sardarsaifali629
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Syntax:

Syntax is just some set of


rules that we must follow to
write code in any
programming language.This
syntax is different for every
language.If we dont follow
syntax of any particular
language whilw writing
code in it then an error will
be ommited.
Source code:
It is the code that a
programmer writes in any
programming language to
give instructions to the
computer.This type of code
is written in normal human
languages like English or
Arabiic etc..
Machine code:
It is the code that computer
understands which is in
form of binary i.e.0 and 1.
Compiler:
A compiler is a program that
converts source code into
machine code because
machine code is not
understandable by humans
and source code is not
understandable by
computers so it sort of
converts
and source code is not
understandable by
computers so it sort of
converts
normal human languages
into the language of 0s and
1s.Compiler in general can
convert any two
languages.
A terminal window is a
command line interface
where we give commands
to our program.It is also
called
prompt.
To create/open a new or
existing le using terminal in
vscode;
fi
write in terminal: code
nameofthe le.c
To compile(convert source
code into machine code)
using terminal in vscode;
write in terminal: make
nameofthe le
To run the program using
terminal;
write in terminal: ./
nameofthe le
.c is an extention for les of
c language
Preprocessor directives:
These are the commands
that give instructions to the
C-compiler.They are usually
used to add different
fi
fi
fi
fi
These are the commands
that give instructions to the
C-compiler.They are usually
used to add different
libraries in the
program.They start with #
sign followed by the word
’include’ or ’de ne’,then the
name of
header le(which contain
set of functions of different
libraries) is written inside <>
these signs.It does not
end with semi colon.i.e.
#include <stdio.h> ,this is
how to add various header
les into programs by using
inculde keyword along
fi
fi
fi
with # and <>signs,.h is the
extention of header
les .stdio stands for
standard io(input/output).
A library is a code that
someone else wrote which
we use for our
convenience.Inside a
library,there are
different functions.Header
les(that ends with .h like
stdio.h)are libraries which
includes functions that we
use repeatedly in our code
but those functions are
actually written by someone
else and included in those
fi
fi
but those functions are
actually written by someone
else and included in those
libraries.There are free as
well as paid libraries out
there which make our
coding experience easy.We
can
add multiple header les in
a program according to our
use.
Details about different
funcions and libraries in c
are found in this page;
manual.cs50.io
Main function;
After preprocessor
directives,this main function
is written(it is not a
keyword).It is used to
fi
After preprocessor
directives,this main function
is written(it is not a
keyword).It is used to
indicate the
beggining of actual
program.Compiler starts
reading from here.If it is not
written,compiler generates
an
error message.It is written
as ’int main()’,inside
patanthesis,one can also
write void.
Delimeters:
After above
statements,body of main
function is started.It is
always written inside curly
braces.All the lines
statements,body of main
function is started.It is
always written inside curly
braces.All the lines
of the code which are to be
executed goes inside these
curly braces.
Keywords:
These are the prede ned
words of c which are used
for special purposes in c
programs.There are 32
keywords in c which are;
[auto break case char const
oat short do double else
enum extern return union
goto if int long register
typedef signed sizeof static
struct switch default
unsigned void volatile while
fl
fi
typedef signed sizeof static
struct switch default
unsigned void volatile while
continue for]
Keyword are always written
in lowercase letters.
Variables:
Varibles are used to store
data to use at different
places during code.It is also
used to store return value,a
return value is something
returned by the user for us
to work on.So we to store
that return value in a
variable to use later.In
c,The name of the variable
remains xed during the
execution of
fi
variable to use later.In
c,The name of the variable
remains xed during the
execution of
program.However,data
stored inside variable may
change as if 2+2 is strored
inside variable
initially.During execution,it
will change into 4 as
compiler will perform
arithmetic operation on
it.Variablesare sort of
memory locations.Declaring
a variable in c is called
variable decleration.In c,its
general syntax
is; type variable ,where type
indicates the type of data
being stored and variables
fi
is; type variable ,where type
indicates the type of data
being stored and variables
is just any random
name we want to assign to
that variable.So for
declaring a variable in c,we
rst need to type down its
data
type name in small letters
and then variable name.i.e.
for a variable having integar
data type;
int variable =
and after equality sign goes
the data being stored in the
variable.
fi
Putting space in name of a
varaible is not allowed.
Special charater are not
allowed(-$%#~!*&^).
Keywords are not allowed.
Assignment operator:
It is an operator that is used
to assign some value to any
container i.e.any
variable."=" considered as
assignment operator is c.
Constants:
Constant is a special type of
varible whose value cannot
be changed during
execution of program.There
are built in constants as well
as user de ned
constants.There value is not
changed,once assign to
them.They help make the
code more readable and
prevent changes to values.
To create a constant in C,
use the const keyword
followed by a data type and
a variable name.i.e.
const int B = 3;
Now,as 3 is assigned to this
constant,it will not change
during execution.
Data type:
fi
Data type de nes the type
of data that can be stored in
a variable or in a broader
view,that can be used in
C program.
Different data types in C:
int;used to store integars,its
keyword is ’int’,its place
holder is ’%i’.
short int;also stores
integars,its keyword is
’short’
long int;store greater
integars ranging from -2^31
to 2^31,its keyword is
’long’.Its place holder is %li.
fi
oat;used to store decimal
point numbers,its keyword
is ’ oat’,its place holder is
’%f’.
double;used to store larger
decimal point values,its
keyword is ’double’,its
placeholder is ’%if’.
long double;used to store
even larger decimal point
values,its keyword is
’long’,its place holder is
’%lf’.
character;used to store one
character(alphabet,integar,s
pecial character or
anything,its keyword is
fl
fl
character(alphabet,integar,s
pecial character or
anything,its keyword is
’char’.It is written inside
single quotes,it does not
use double quotes as well
like string literals.It is
different
from string data type as it
can store only one
character while string is an
array of characters(it can
store
many characters).It splace
holder is ’%c’.
Boolean;used to store 1 or
0 i.e. yes or no.Its keyword
is ’bool’.There is no place
holder for bools.
0 i.e. yes or no.Its keyword
is ’bool’.There is no place
holder for bools.
Operators:
These are special symbols
used to perform different
operations in a program.
Types of operators:
Arithemetic operators;these
are used to perform
different arithmetic
operations on
data.addition(+),subtraction(
-),multiplication(*),division(/)
and modulous(%)(it is used
to get remainder of
two values)are arithmetic
operators.
Operators precedence;the
order in which arithmetic
operators are formed is
called operator
precedence.Operators
having higher precedence
are evaluated
rst.Paranthesis have
highest
precedence,then
multiplication and division
both having same
precedence(they are
evaluated from left to
right) and then addition and
subtraction.
fi
Compound assignment
statement:
This is a statement that is
used to assign a single
value to multiple
variables.i.e.to assign 18 to
va ables a
b and c; a = b = c = 18.
Type casting:
It is the process of
converting one data type to
another data type for
performing arithmetic
operations.
Explicit casting;It is the type
of casting which is not done
automatically by c-compiler
and user needs to
fi
Explicit casting;It is the type
of casting which is not done
automatically by c-compiler
and user needs to
do that.Its general syntax is;
(type in which we want to
convert) expression to be
converted(any value or
variable).i.e.to convert
oating
number 3.1234 to integar;
(int)3.1234 ,now this
statement goes inside print
statement like;
if a = 3.1234and we want to
convert it into an
integar,print statement will
go like this;
fl
printf("%i\n", (int)a);
the placeholder here will be
written according to the type
in which we are going to
convert which here in
our case is integar.
It will be converted to 3.
Typecasting can be done
like this as well;
int a , b;
float sum;
a = 12 , b=5;
sum = a/(float)b;
printf("%f\n", sum);]
Implicit typecasting;it is
done by the compiler
automatically.
Implicit typecasting;it is
done by the compiler
automatically.
Truncation:
It a term which literally
means to cut down.When
an int type number is
operated with another int
type
number then their answer
will be also in int type
number no matter what.If its
answer is in decimals,the
digits after decimal point will
be truncated and only 1
number will be given as
output even if we typecast
the variable containing their
answer it will still not give
accurate answer.So what
the variable containing their
answer it will still not give
accurate answer.So what
we have to do is to
typecast both variables
containing those int and
also declare the variable
with their answer as oat to
get
the answer in oat.So
typecasting is done on
variables being used not on
their
answer.However,variable
containing answer,must be
in type in which you want
the answer to be.
fl
fl
Comment statements:
These statments are non
executable statements in
the code.They are used to
add comments in the
program.These lines are not
executed by compiler.They
enhance the readibility of
program.To use it
enclose your statment with /
*,*/.i.e.start your statement
with /* and end with */.For
commenting a
statment;
/*This is a comment*/,this
line of code will not be
exececuted but will be
visible in code.This method
/*This is a comment*/,this
line of code will not be
exececuted but will be
visible in code.This method
is
used when we have to
comment down multiple
lines of code but if we want
to comment down just one
line
of code we can just do // at
start of the line.These are
used as sticky notes to add
some information about
your code or if you want to
highlight something so to
remember in future.
Placeholders:
These are used with %
sign.They are used to input
the value of the related data
type by using them inside
quotation marks and after
quotation marke variable
name seperated by a
comma.The value of the
variable is displayed in
place of given
placeholder.Place holders
are always written inside
quotations.Usually,in c
variables are not included
inside quotation marks so to
put the value stored in the
variable we use place
holder or format speci ers
inside quotation marks
along with rst letter of the
data
type and after quotation
marks put a comma and
then variable name.For
using a variable in which
string
data is stored we use %s
inside quotes and then after
ending quotation marks,a
comma and then variable
name.Example of such
code is;
fi
fi
printf("hello, %s",
variablename);
When working with various
variables and using them in
single statement,order of
variable matters.As
format speci er for
variables of same data type
is same, so to tell the
compiler when to execute
which you
need to place that variable
after quotataion marks in
respected order.For
example,if there are 2 int
variables a and b and you
want to use b before
a.a=25,b=34;the statement
fi
variables a and b and you
want to use b before
a.a=25,b=34;the statement
will go like;
printf("%i is greater than
%i", b,a)..Notice here,format
speci er for both these
variables is same but it will
output the statement as 34
which is b greater than 25
which is a just because we
have placed b variable
before a after quotation
marks.This can be done
with as many variables
aswe can like
3,4,5,6,7...just
fi
keep in mind the order to
use the,.
Place holder for string data
type is %s.for integars is %i
or %d,for oat(decimals) is
%f.
A format speci er is also
used in scanf function to
specify the type of data
according to which data
going
to be input.
Escape sequence:
This is a combination of a
special character with a key
letter to perform a spece c
task like for
fl
fi
fi
special character with a key
letter to perform a spece c
task like for
example;for going to next
line,escape sequence used
is \n.\(back slash)is the
special character used with
different key letters.These
are not literally printed in
the output but use for
performing some tasks.
List of different escape
sequences;\n;used for
going to next line
\t;used for inserting a tab
space in output
\a;used to make beep
sound
fi
String variable:
A string is a colection of
characters.A variable that is
used to store strings is
called string variable.
Scanf function:
Scanf cuntion is used to get
input values from the user
into a variable.This function
can be used to get
input into numeric,character
and string type
variables.Inside scanf
function the input data type
must be
specei ed using format
speci ers inside quotation
marks.In this function,only
fi
fi
fi
specei ed using format
speci ers inside quotation
marks.In this function,only
format speci ers are written
inside quotes,no other text
is written like that in printf
function.If we want to write
soe text we will have to
use a printf function before
scanf function.Also the
variable being used should
be declared rst along with
its data type.The general
syntax of scanf function is;
scanf("format speci er",
variable);
Here inside quotation marks
only format speci er of the
variable being used inside
fi
fi
fi
fi
fi
fi
Here inside quotation marks
only format speci er of the
variable being used inside
scanf function is
written,no other text.and
then variable name.
Semi colon:
It is known as statement
terminator.It is used to
terminate a statement so it
is written at the end of
almost
each statement.
Compound assignment
operators;these operators
provide shortcut ways for
adding,subtracting,multiplyi
ng or dividing to and from a
variable.These are +=,-
fi
adding,subtracting,multiplyi
ng or dividing to and from a
variable.These are +=,-
=,*=,/+,%=.i.e.for adding 5
to variable x; x += 5
Increment operators:
These are sortcut ways of
adding or subtracting 1 from
a variable.These are used
by just writing two
signs(+ or -) next to the
variable and then statement
operator.Suppose theres a
variable name A and you
want to add one to it,its
syntax will go like this;
A ++;
Its always better to use
spaces in your
code.However,it can be
done without spaces like
this;A++;.
Conditionals:
These are the keywords in
C that make decisions
according to certain
conditions.Commonly used
conditionals in C are;if,else
if and else.They usually
compare two variables and
then make a decision
according to given
condition.General syntax of
conditionals is;
according to given
condition.General syntax of
conditionals is;
if (condition 1)
{
statements...;
}
{
else if (condition 2)
statements...;
}
{
else if (condition 3)
statements...;
}
{
else
statements...;
)
Here condition is any
condition which you will put
to compare two things like if
x>y or x<y or any other
condition.Statements are
the set of lines which will be
executed if the condition of
that particular block is
true for example if condition
of if is true it will enter in
theif block and execute its
statements and skip other
else if and else blocks and
stops.If rst condition is not
true it will check the next
else if contition,if it is true
fi
stops.If rst condition is not
true it will check the next
else if contition,if it is true
it will enter into it,executes it
and stops.If no condition is
true then else block is
executed nally.
Example;
{
int marks;marks =
get_int("Enter your
marks:");
if (marks > 33)
{
printf("You have passed!:
%i\n", marks);
}
{
fi
fi
else
printf("You have failed!:
%i\n", marks);
}
}
You can make as many
blocks as you want with
different condition.Else
block can be written only
once at
the end while else-if blocks
can be unlimited.An if block
indicates the starting of
whole new story of
decisions thats why we use
else-ifs.However,various if
blocks can be written inside
the body of an if
decisions thats why we use
else-ifs.However,various if
blocks can be written inside
the body of an if
block.Thats called "nested if
statement".Its synyax is;
if (condition 1)
{
if (condition 2)
{
statements...;
}
{
else
statements...;
}
else
{
staements...;
}
1.0
{
*To get answer in form of
points you need to perform
arithmetic operations on
oats.If you have whole
numbers but you want to
get the answer in oats then
just use a point and 0 with
the whole number like
A program that inputs
obtained marks of a student
and after calculating
percentage,gives his grade;
fl
fl
int marks = get_int("Enter
your marks: ");
int average = marks /
1200.0 * 100;
printf("%f\n", average);
if (average >= 80)
{
printf("Your grade is A+\n");
}
{
else if (average >= 70)
printf("Your grade is A\n");
}
{
else if (average >= 60)
printf("Your grade is B\n");
}
{
else if (average >= 50)
printf("Your grade is C\n");
}
{
else if (average >=
40)printf("Your grade is
D\n");
}
{
else if (average >= 33)
printf("Your grade is E\n");
}
{
else
printf("Your grade is F\n");
}
}
A program that asks yes or
no;
char a = get_char("Do you
agree? (y/n):");
if (a == ’y’ || a == ’Y’){
printf("Agreed!\n");
}
else if (a == ’n’ || a == ’N’){
printf("Not Agreed!\n");
}
else {
printf("Give your answer in
y/n!\n");
}
Note:All of the above
programs are written using
cs50’s library so there are
some built functions which
we
wont nd in real world
programming like get_int.
Relational operators:
These operators are used
for comparing two values of
the same type.They are
mostly used in conditional
and loop constructs.They
are also called conditional
operators or comparison
operators.
fi
are also called conditional
operators or comparison
operators.
Different types of operators:
Equal to(==);this is used to
check/show equality b/w
two values.
Not equal to(!=);this is used
to show/check inequality b/
w two values.
Greater then and less
then(<>);these are used to
show/check if one value is
greater then or less then the
other.
Greater then or equal to
and less then or equal
to(>=,<=);these are used to
check if one value is greater
and less then or equal
to(>=,<=);these are used to
check if one value is greater
then,equal to or less then
equal to the other.
Logical operators:
These operators are used
to combine two or more
conditional operators.THis
combination is called
compound expression.
Different logical operators:
AND(&&);this is denoted by
double ampersand sign b/w
two conditional
operators.This operator and
the
two conditional operators
are written inside a greater
parenthesis which include
two conditional operators
are written inside a greater
parenthesis which include
two parenthesis of the
two conditions and between
then this sign.It returns
true(its block is
executed)only if both
conditions are
true.
You can use this by adding
everything i.e.all conditions
and the logical operator in
one single paranthesis
like;
(x>=1 && x<=10)
it will return true only if both
of these are true.
it will return true only if both
of these are true.
OR(||);this is denoted by
double pipe sign(||) b/w two
conditional operators.This
operator and the two
conditional operators are
written inside a greater
parenthesis which include
two parenthesis of the two
conditions and between
then this sign.It returns true
if any of the condition is
true.i.e
You can use this by adding
everything i.e.all conditions
and the logical operator in
one single paranthesis
everything i.e.all conditions
and the logical operator in
one single paranthesis
like;
(x>=1 || x<=10)
it will return true if any of the
condition satis es.
NOT(!);this is denoted by
exclaimation sign(!) before
the condition as it is used
with only one condition
butinside a greater
parenthesis along with
smaller paranthesis of
condition.It reverses the
condition like if the
condition is that if x is
greater than y
print;"Yeah!"else
print;"Heck!".Using not
fi
condition is that if x is
greater than y
print;"Yeah!"else
print;"Heck!".Using not
operator will reverse the
condition i.eit will print heck!
if x is greater and print
yeah! if x is smaller.It is also
called negation operator
as it negates the
condition.Its syntax is;
if (!a > 5)
Return value:
A value that a user or a
function returns when it is
competed.A return value is
usually stored inside a
variable.
*A single indent(tab
space)is of four spaces.
Loops:
These are functions in C
which keep repeating
certain lines of code.The
lines of code that are
executed
repeatedly are called body
of the loop.The body of the
loop can be executed for a
spece c number of
times or as long as the iven
condition remains true.
Types of loop in C:
The ’while’ loop;this kind of
loop keep executing as long
as the condition remains
fi
The ’while’ loop;this kind of
loop keep executing as long
as the condition remains
true.The general syntax
of while loops is;
while (condition)
{
}
Here while is the keyword
used for while
loop,condition is the
condition of the loop.It is
written inside
parenthesis and the inside
curly braces are the
statements of while loop
which is also called body of
loop.When while loop is
executed,condition is
checked rst,if it is true the
statements of loop will sbe
executed.Then it will come
back at top to check the
condition again.If it is still
true it will execute
again.This cycle will keep
repeating as long as
condition is true.Once
condition becomes false,the
loop is
terminated.i.e.
Table of any number using
while loop;
fi
{
int number = get_int("Enter
any number: ");
int table = 1;
while (table < 11){
int product = number*table;
printf("%i X %i = %i\n",
number,table,product);
table++;
}
The ’for’ loop;this kind of
loop is used when we know
exactly how many times we
have to repeat the
code.This loop is also
known as counter loop.The
general syntax of for loop is;
code.This loop is also
known as counter loop.The
general syntax of for loop is;
for (initiliazation; condition;
increment/decrement)
{
body of loop(statments to
be printed)
}
Here,initilization means
initilizing variables.In for
loop,variables are not
initilized inside pr outside
loop but
while declaring the
loop.Multiple variables can
be declared here,each
seperated by
comma.Initilization
be declared here,each
seperated by
comma.Initilization
ends with a semi colon. i.e.
for (int x =1, y = 2; and then
other parts)
Condition means the
condition which is checked
everytime.The code keep
getting execited as long as
condition is true.It also ends
with a semi colon.
Then if we want to
increment or decrement
anything inside declared
variables comes in.Multiple
incrementations or
decrementations can be
performed here.It does not
ends with semi colon.
incrementations or
decrementations can be
performed here.It does not
ends with semi colon.
Table of any number using
for loop;
for (int n = get_int("Enter
any number: "), t = 1, p =
n*t; t < 11; t++){
printf("%i X %i = %i\n",
n,t,p);
A for loop can become an
in nite loop if there is no
condition given.i.e.
for (int i = 0; ; i++)
Semi colon is neccessary
even if condition is missingA
while loop can also become
in nite loop only by writing
boolean expression true in
fi
fi
even if condition is missingA
while loop can also become
in nite loop only by writing
boolean expression true in
place of condition.It
will perceive the condition
as true always and keep
executing the code
in nitimisely.i.e.
while (true)
The main function is very
crucial.It indicates the
starting of code i.e code
start to execute from
here.Any
library or function must be
written outside of it
otherwise it will omit an
error.Every program can
only have
fi
fi
written outside of it
otherwise it will omit an
error.Every program can
only have
one main() function.So all of
executable code is written
inside of it while libraries or
user-de ned functions
can be written outside of it.
The ’do-while’ loop;It is also
used to execute a set of
statements as long as the
given condition remains
true.It is a peculiar kind of
loop as it takes statements
before condition.As
apparent from its name,it
literally asks to do
something while any
condition is truei.e.it takes
fi
literally asks to do
something while any
condition is truei.e.it takes
condition after writing the
code of its
operation.While the other
loops takes condition
before,it take it after.The
body of the loop comes
before
the test condition.So the
body of the loop is executed
atleast once.It is usually
used to ask something
from user like menu
selection as these kind of
procedured must be done
atleast once.The general
syntax
selection as these kind of
procedured must be done
atleast once.The general
syntax
of ’do-while loop is;
do
{
body of loop;
}
while (condition);
Here,at start keyword do is
written and then inside curly
braces body of loop i.e. set
of statements of its
operation are written and
then after ending curly
braces in next line or in the
same line(where ending
curly
braces in next line or in the
same line(where ending
curly
braces is) while keyword is
written along with the test
condition of loop and a semi
colon.For do while loop
a semi colon must be
passed after test condition
with while keyword.Example
of do while loop is;
int n;
do{
n = get_int("Enter size: ");
}while (n < 1);
This test condition can also
be written in next line.While
using do-while,we dont
need to intialize variable
be written in next line.While
using do-while,we dont
need to intialize variable
being used in it but
declaring them is must.
Functions:
A function is a peice of code
which is written to perform a
spece c task.It is just like a
library just that
library are built in or pre
de ned functions while
functions are user de ned
i.e we de ne them inside
the
program.It is independent of
the remaining code of the
program.Just that its call is
used inside main()
fi
fi
fi
fi
the remaining code of the
program.Just that its call is
used inside main()
function,that is when a
function is executed.It can
be used then at different
places at different times
inside
main() function.Each
function has a unique
name.It is called with its
name by using a set of
parenthesis
with it and then a semi
colon i.e. name();.
Function prototype/Function
decleration:
Declaring the user de ned
function is called function
prototype.It is different from
fi
fi
Declaring the user de ned
function is called function
prototype.It is different from
function de nation.It is a
single line of code which
includes the return type of
function,function name(with
reference to which it will
be called inside main()
function) and then inside
parenthesis,parameters(the
se are variables which are
to
be used inside the function
and then while calling the
function,inside
paranethesis.They are just
declared
fi
fi
function,inside
paranethesis.They are just
declared
here i.e. their data type and
name is speci ed.If there
are multiple parameters
they are written seperated
by commas and then while
calling arguments(these are
values passed to
parameters inside
paranthesis
of funtion call) are passed
to them also seperated by
commas).It just provides the
compiler neccesary
information about function,it
does not include the proper
code of function(that is for
function de nation).It
fi
fi
information about function,it
does not include the proper
code of function(that is for
function de nation).It
is usually used before main
function(at start) to inform
compiler about the
function.However,it can also
be
declared inside main
function.Its general syntax
is;
return-type function-
name(paramters);
If there is no return value
then just use ’void’ keyword
in place of return-
value.Similarly,if there are
no
fi
in place of return-
value.Similarly,if there are
no
paramemters then also use
’void’keyword inside
paranthesis.i.e.
void func-name(void);
Semi colon is always used
when it is declared before
main function.
Function defination:
This is the set of code that
performs different
operations of the function.It
is always written outside the
main() function,either after it
or before it(at start).If
function de nation is written
before main() functionthen
function decleration is not
fi
or before it(at start).If
function de nation is written
before main() functionthen
function decleration is not
required but it is not
conventional as it takes a
lot of space at start so its
better to use prototype at
start and de ne the function
outside main function.A
function can also be saved
as a seperate le and then
be used inside different
programs by #include
keyword and then name of
le
with .h.General syntax of
function de nation is;
fi
fi
fi
fi
fi
return-type function-
name(parameters)
{
set of statements
}
Here rst line is similar to
function prototype just that
while de ning,semi colon is
not used.It is only
compulsory while declaring
seperately.This part is
called function header.If
there is no return value then
just use ’void’ keyword in
place of return-
value.Similarly,if there are
no paramemters then also
use
fi
fi
place of return-
value.Similarly,if there are
no paramemters then also
use
’void’keyword inside
paranthesis.i.e.
void func-name(void);
Then is function body.Inside
of it is all the code.This
peice of code cannot be
written inside main()
function.However,function
prototype can be written
inside main function but the
most conventional way is
to declare the function at
start and then after main
function,de ne it.
fi
Function call:
A statement that is used to
execute the code of a
function is called function
call.A function is called with
reference to its name and
then a set of paranthesis.If
functions has parameters
then arguments i.e actual
values are also written
inside paranthesis
seperated by commas.If
there are no arguments to
pass,just
keep the paranthesis
un lled.
fi
-It is not compulsory to
declare the function at
top.We can do it inside the
main function as well.The
things
which are compulsory are to
de ne the function out of int
main() function(either at top
or bottom) and to
declare a function atleast
once(either inside int main()
function or at start).We
must declare the function
i.e write its decleration
statement before calling the
function whereas function
de nation can be made
fi
fi
statement before calling the
function whereas function
de nation can be made
after calling it i.e in next
lines.
Example of simple function;
#include <cs50.h>
#include <stdio.h>
void meow(void);
int main()
{
meow();
}
{
void meow(void)
printf("meow\n");
}
Here function declerator is
at start.However it can also
come down inside int main()
fi
Here function declerator is
at start.However it can also
come down inside int main()
but it cannot go
beyond that as function is
being called inside int
main().Function de nation
can also be written at top
just
that it cant go inside of int
main();
#include <cs50.h>
#include <stdio.h>
void meow(void)
{
printf("meow\n");
}
fi
{
int main()
void meow(void);
meow();
}
Function parameters:
These are variables along
with their data types written
inside paranthesis in
function decleration and
de nation.These are
variables that pass actual
values while calling the
function.Formal
paramters;The parameters
that are used in function
header of function
decleration or de nation
fi
fi
paramters;The parameters
that are used in function
header of function
decleration or de nation
are called formal
paramters.They must be in
form of variables along with
their data types.We dont
have to
assign any value here
because they are passed to
them during function call
inside paranthesis.If there
are multiple paramters,we
have to write each
seperated by comma with
its own data type
seperately.
fi
fi
Actual parameters;These
are the actual values
passed to the function
during function function call
inside
paranthesis.If there are
multiple parameters,so
multiple values are
assigned each seperated by
comma in
respected order.Their data
type must match with data
type of formal
parameters.Actual
parameters are
also called arguments.For
passing arguments we dont
need any scanf function or
also called arguments.For
passing arguments we dont
need any scanf function or
get function because
arguments are not passed
by the user but by the
programmer itself so he just
have to declare the formal
parameters and then just
pass the arguments while
calling the function.Not only
we can just pass
numbers to these
arguments but variables
and constants as well.Like
the variables containing
some data
which can be used in that
function.
Function with a for loop;
#include <cs50.h>
#include <stdio.h>
void meow(int n);
int main()
{
meow(5);
}
{
void meow(int n)
for (int i = 0 ; i < n ;i++){
printf("meow\n");
}
}
Another function with for
loop but without
parameters;
#include <cs50.h>
#include <stdio.h>
void meow();
int main()
{
meow();
}
{
void meow()
for(int i = 0 ,n =
get_int("Enter how many
time it should \"meow\": ");i
< n;i++){
printf("meow\n");
}
In for loop,when declaring
variables of same type we
must write the data type key
word once and then all
variables associated with
that data type seperated by
commas.If we want to do
anything with those
variables,we must do it in
that very statement like
getting any input from user.
Return value:
When a function completes
its execution,it may return
some value to the calling
function as ouput.It can
When a function completes
its execution,it may return
some value to the calling
function as ouput.It can
be any value like digit or
some formula.Contents of
printf function are not
included in it.It returns any
value
when return statement is
used.The type of data that a
user de ned function
returns must be declared
while declaring or de ning
the function.If a function
returns no value i.e it just
returns printf contents then
void keyword is used.
fi
fi
Return statement:
It is a special sort of
statement which is used
inside the body of function
to return any value to
function
call as well as execution
control means where this
statement is used execution
ends there.Thats why this
statement is usually used at
end of the function because
it executed no more code
after it.Its general
syntax is;
return expression;The
expression can be
anything,a variable,an
return expression;The
expression can be
anything,a variable,an
expression consisting of
variables or numbers or
even
constant,viz;it is the thing
whose value you want to
return.
When this statement is
used we have to specify the
type of data it is returning
while declaring or de ning
the function.
Ben ts of using Return
statement:
Biggest advantage of using
return statement is that we
can store the value returned
fi
fi
Biggest advantage of using
return statement is that we
can store the value returned
by the return
statement to the function
call in any variable.i.e.if we
have a function name sum
which uses a return value
then we can store its value
inside a variable;
a = sum(3,5);
Now we can use this
variable whenever we want
to access the contents of
that function.
Not only this we can apply
different arithmetic or other
operations as well with
function call inside this
Not only this we can apply
different arithmetic or other
operations as well with
function call inside this
variable;
a = sum(3,5) * 10;
Another advantage is that
we can then use the
function call inside any
output function to directly
output
the contents of that function
along with other
information;
printf("sum = %i", sum(2,3));
What return value actually
does it that we dont need to
store the returned value in a
avraible.Because
does it that we dont need to
store the returned value in a
avraible.Because
when we take any value
from user inside a variable
or do any arithmetic
operation inside a variable
so
that value is returned to that
variable and stored
there.So to print it then we
will have to use printf
function
seperately with that variable
in which return value is
stored.But with return
statement,we can save
some
strokes and directly print the
value returned.If we are not
using return statement that
what we will have to
do is to store our return
value in a varaible and then
print that variable using
printf function and all of
these
things are happening inside
function so when we have
to call it,we cannot store it
inside a variable
because printf function
cannot be stored in any
variable nor we can print it
out with other text as we
cannot be stored in any
variable nor we can print it
out with other text as we
cannot use printf function
inside of another printf
function so there are a lot of
bene ts of using return
statement because then we
wont need inside function to
store the value in any
variable,we wont need to
print the function all that will
be done with return
statement and then while
calling we can assign our
function to any variable or
even use it inside a printf
function.Using a function
inside a printf function can
fi
even use it inside a printf
function.Using a function
inside a printf function can
be think of as function
composition which we do in
calculas which is to just
compose different functions
into one another.So with
return statement we can do
function composition as
well.A return value is just
like a variable just that it
does not store the value in
itself though value is stored
in function in which return
statement is being uses.
Scope of a variable:
Scope is the block of code
or region where a variable
is declared.Now the thing
Scope is the block of code
or region where a variable
is declared.Now the thing
why scope is important is
that if any variable is
declared at any region
which is known as scope of
a variable,then that variable
can
only be used in that
particular region or
scope.There are mainly two
categories of regions or
scopes for a
variable.The use of a
variable is con ned to the
most recently opened curly
braces i.e. in the curly
braces
fi
variable is con ned to the
most recently opened curly
braces i.e. in the curly
braces
it is declared.
Local variables;these are
the variables that are
declared in the scope of any
function i.e. inside of any
function.These variables
can only be used in that
particular function not in any
other function.Any variable
which is declared in,lets
say,int main() function can
only be used inside of int
main() because int main() is
also itself a function.
fi
Global variables;these are
the variables which are
declared globally i.e.outside
of any function.They are
not inside curly braces of
any function.They are
usually declared at top of
each program.Now the
beautiful
thing about global variabkes
is that they are accessible
to every function inside that
program.They can be
used in multiple function
and we dont need to
declare them seperately in
each function.
and we dont need to
declare them seperately in
each function.
Command line interface:
An interface with which a
user can interact through
keyboard is called
command line interface.It
takes
commands in form of
text.Terminal window or
propmt is an example of
command line interface or
CLI.These kind of terminals
mostly uses linux operating
system.
Graphical user interface:
An interface with which a
user can interact thorugh
graphical objects is called
An interface with which a
user can interact thorugh
graphical objects is called
graphical user interface.It
uses menus and buttons for
inteeraction.It is also called
GUI.
Now GUI is very easy its
just clicking with our mouse
or double clicking and
dragging things but CLI is a
bit pain l because we have
to give a textual command
for literally every
action,even to open a new
le orany existing le and
you cant just make up
commands yourself. There
are pre-de ned commands
fi
fl
fi
fi
le orany existing le and
you cant just make up
commands yourself. There
are pre-de ned commands
which
we use to perform different
trivial everyday actions
which we take for granted in
GUI.
Some basic commands of
CLI:
-going to any other folder;cd
foldername(which you want
to go into).That folder must
exists in the existing
directory.So if you want to
check which folders exists
in that existing directory just
use ls or dir command.
fi
fl
fi
fi
check which folders exists
in that existing directory just
use ls or dir command.
-making new folder;md
foldername(it is just used in
windows powershell/mkdir
foldername
-rename newfolder;ren
foldername newname(it is
just for windows
powershell).mv is what can
be used
commonly for renaming
directories as well as les.
-deleting a folder;rd(its just
for windows powershell)/
rmdir foldername.This is
spece cally used for
fi
fi
removing folders not for
les.For les,the command
is rm.
-making multiple
directories;md
foldername\innerfolder......
(just for powershell)
-renaming a le;ren
lename.txt newname.txt
-return from a folder;cd..
(just for windows
powershell).
-directly go to c drive;cd\
(just for windows
powershell).
-directly going to any
folder;just copy its location
from the location bar and
fi
fi
fi
fi
-directly going to any
folder;just copy its location
from the location bar and
then paste in prompt after
typing cd and space
-copy les from one drive to
other;xcopy /h /i /c /k /e /r /y
drivename: 2nddrivename:
or just cp and then
folder name.
-code lename.language
extention;this is used to
create a new le for coding
in respected language.It
can
also be done in every
terminal.It will direct to
default code editor.It can
also be used to open a
fi
fi
fi
also be done in every
terminal.It will direct to
default code editor.It can
also be used to open a
existing
file.
-make lename;this is used
to compile the code.
-./ lename;this is used to
run the code.
-mv previous- lename. le-
extention new- lename. le-
extention;this is used to
rename a le.mv means
move.It can also be used to
rename directories
-ls;it is used to list all of les
in a particular folder.just
write ls and boom!.ls means
list.dir can also be used
fi
fi
fi
fi
fi
fi
fi
fi
-ls;it is used to list all of les
in a particular folder.just
write ls and boom!.ls means
list.dir can also be used
for this purpose
-rm;this is used to remove a
le from any directory.just
write rm lenam. le
extention and then they will
ask if we really want to
delete the le so then we
just have to type y or n.
cd;cd alone(without any
folder name or .. or \) is
used commonly for coming
to mother directory like it
will
exit all the subfolders at
once and come at the
original folder where all
fi
fi
fi
fi
fi
exit all the subfolders at
once and come at the
original folder where all
those folders were
created.It kind
of takes you back home.
Nested loops:
These are just some loops
made inside of other
loops.The syntax of both
the loops is same just that
we
compose them.Different
patterns that we make in
code are good example of
using these nested loops.
Example of simple 10x10
star pattern using nested for
loop.
Example of simple 10x10
star pattern using nested for
loop.
#include <stdio.h>
#include <cs50.h>
int main()
{
int n = 10;
for (int i = 0;i < n;i++){
for (int j = 0;j < n;j++){
printf("*");
}
printf("\n");
}
So lets break this down; rst
of all,a variable n is declare
which will determine its
dimensions.Then a for
fi
of all,a variable n is declare
which will determine its
dimensions.Then a for
loop is started which do
something as long as i is
less then n which is 10 so it
do anything 10 times.If we
wont use another loop
inside of that loop it will just
print 10 stars either
vertically or
horizontally(vertically if
we use \n and horizontally if
we dont use \n.But we need
here 10 stars on every line
means 100 stars so
we will make another for
loop with n = 10 because if
we use n = 100 in one loop
only it will not print on
fi
we will make another for
loop with n = 10 because if
we use n = 100 in one loop
only it will not print on
each line but all 100 in one
line.So we use another loop
with printf inside of it.But
what we see is that this
time it did print 100 stars
but all on same line either
on vertical or horizontal.So
what we need is that after
completing every 10 stars it
should go to next line
repeatedly 10 times.So we
need it to go to next
lineafter every 10
repetitions so we make a
printf statement with new
line character only after the
lineafter every 10
repetitions so we make a
printf statement with new
line character only after the
inner loop
but inside of outer loop.Now
it did perfectly what we
wanted it do.So what
happens actually.When the
control entered outer loop it
directly went into inner loop
which was printing star 10
times in single line so
when inner loop printed 10
stars in single(because we
did not use \n in its printf()
as compiler naturally
prints everything in single
horizontol line when loop is
used in every repition so we
prints everything in single
horizontol line when loop is
used in every repition so we
use \n and it pushes it
on the next line after each
iteration.)control went out of
it and encountered the new
line character printf
waiting there which was
part of outer loop so it
pushed it onto next line.So
hitherto,10 stars got printed
and control is on next line
but loop is not over yet as
outer loop was also set to
perform 10 iteration so it
returns to top from where it
enters the inner loop again
print 10 stars in single line
returns to top from where it
enters the inner loop again
print 10 stars in single line
then get to \n after loop
and got pushed to next
line.It repeats it 10 times
resulting a 10x10 block of
stars because thanks to
inner
loop,10 stars were etting
printed in each horizontol
line and thanks to outer
loop the number of these
horizontol lines(each with
10 stars)was set to 10.We
can make various patterns
by using this techniqe we
just have to play with
iterations of outer and inner
loops.And make some other
minor changes.
While loop is not suitable for
this kind of code because a
while loop is used when
dont know the number
of iterations.
-The compiler naturally
perform every iteration
horizontally.
-Linux terminal remember
our last written command so
we can call it directly by just
pressing up arrow
button and it will be
automatically written(our
last used command).Not
only last used but few of
them like
few of last used commands
not only one.
This peice of code debare
user from giving any illogial
size like 0 or in negative;
#include <stdio.h>
#include <cs50.h>
int main()
{
int n = 0;
while (n < 1){
n = get_int("Enter size: ");
}
for (int i = 0;i < n;i++){
for (int j = 0;j < n;j++){
printf("*");
}
printf("\n");
}
}
-Bear in mind that counter
of comipler moves through
lines in order so if once the
code of previous line is
successfully compiled it
would move further.It moves
through every line and
check every word written.
would move further.It moves
through every line and
check every word written.
Integar overflow:
In any computer or this sort
of device,there are nite
many bits i.e.there is a limit
to which we can store
our data.If we try to go
beyond that limit,it returns
to 000....This is called
integar over ow.This
happens
with variables as well.Some
variables support 8 bits
some,32 and some even 64
and hence the limit of
maximum data storage
vary.For example,in a 32 bit
supported variable,we can
fl
fi
maximum data storage
vary.For example,in a 32 bit
supported variable,we can
store a number as big as
4 billion but if we want to go
neyond that even by 1
number,it will wrap around
0.i.e.integar over ow
happens.int data type
support 32 bits and long
data type(long integar)
support 64 bits means it can
almost
count up to in nity.Double
also uses 64 bits wheares
oat uses 32 bits(but they
are for oating point
fl
fl
fi
fl
numbers).
Floating point imprecision:
This is used inside printf
with oat data type.It is
used if you are getting
in nite digits after point so
through
this trick you can actually
choose how many digits
you want after decimal
point.It syntax is just to
write%.how many
numberse you wantf,here,%
is place holder symbolthen .
is part of syntax and then
type the number you want
the digits and then f which
is place holder for oat.So
fi
fl
fi
fl
type the number you want
the digits and then f which
is place holder for oat.So
lets say you want ve
digits after decimal point
and your value is stored in
variable x:
printf("%.5f", x);
But what is imprecision?It is
that if you want to get lets
say 20 digits,it will give
some inaccurate digits
because computer memory
is nite and it cannot store
in nite digits so it just round
off those in nitimiselybig
numbers which gives us
mathematically inaccurate
numbers.If we dont use this
fi
fi
fi
fi
fl
off those in nitimiselybig
numbers which gives us
mathematically inaccurate
numbers.If we dont use this
%.xf thing,computer
give us 4 to 5 digits by
default which are not that
big so they are accurate.So
when we use and we ask it
to give some huge number
it just cant t inside
computer’s nite memory.
-Memory get reset when
device is turned off and
then on.So all of the bits
that were used last time set
to 0
again.But if you are making
something that is not turned
off often so its gonna be a
fi
fi
fi
fi
fi
again.But if you are making
something that is not turned
off often so its gonna be a
problem.
Left aligned pyramid;
#include <stdio.h>
#include <cs50.h>
int main()
{
int n;
do
{
n = get_int("Enter the height
of pyramid(0-100): ");
}while (n <= 0 || n > 100);
for (int j = 0;j < n;j++)
{
for (int i = 0;i < j+1;i++)
{
printf("#");
}
printf("\n");
}
}
Problem set 1:
*Right alligned pyramid;
#include <stdio.h>
#include <cs50.h>
int main()
{
int n;
do
{
n = get_int("Enter the height
of pyramid(0-100): ");
}
while (n <= 0 || n > 100);
int n2 = n;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n2-1; i++)
{
printf(" ");
}
{
for (int k = 0; k < j + 1; k++)
printf("#");
}
printf("\n");
n2--;
}
}
Output: ###
###
*Double pyramid;
#include <stdio.h>
#include <cs50.h>
int main()
{
int n;
do
{
n = get_int("Enter the height
of pyramid(0-8): ");
}
while (n < 1 || n > 8);
int n2 = n;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n2- 1; i++)
{
printf(" ");
}
{
for (int k = 0; k < j + 1; k++)
printf("#");
}
{
for (int l = 0; l < 2; l++)
printf(" ");
}
{
for (int m = 0; m < j + 1; m+
+)
printf("#");
}
printf("\n");
n2--;
}
}
Output: # #
## ##
### ###
-Only thing i learned by
doing this excercise is that
by giving enough time and
not giving up while
constantly trying to solve
the problems by applying
different approaches,you
will get there with the help
of
Allah.Inshallah!
Coins return calculator;
#include <cs50.h>
#include <stdio.h>
int main()
{
int cents = 0;
int change;
do
{
change = get_int("Change
owed: ");
change = get_int("Change
owed: ");
} while (change < 0);
int quarters = change / 25; //
Quarter cents(25)
int q2 = change % 25;}
int dimes = q2 / 10; // Dime
cents(10)
int d2 = q2 % 10;
int nickels = d2 / 5; // Nickel
cents(5)
int pennies = change % 5; //
Pennies(1)
int coins = quarters + dimes
+ nickels + pennies; //Total
coins returned
printf("%i\n", coins);
By giving enough time and
thinking to every problem,by
applying different
approaches any problem
can
be solved with the help of
Allah.Inshallah

You might also like