Вы находитесь на странице: 1из 112

Introduction to C Program

WIn 1960, at Cambridge University at USA, a


powerIul and basic language was developed
known as B language.
WOriginal name oI B-Language is Basic Combined
Programming Language (BCPL).
WAIterwards the BCPL was renamed as 'C
Language.
WDennis Ritchie had developed C-Language in
1972 at 'Bell-Laboratories in USA.
%here exist three important areas in typical C Program such as:
1. Include Block
2. Function Block
3. Main Block
# .
# .
# .
include stdio h
include math h Include Block
include string h

()

}
main
Main Block

Sample program: Printing a Message


maln() luncLlon name
sLarL of Lhe program

rogram sLaLemenLs

end of Lhe program


main()

/* ... Printing begins....*/


printI('I see, I remember);
printI('I see,\n I remember !);
/* ... Printing ends....*/
}
Output: I see, I remember
I see
I remember !
Constants, Variables and Data %ypes
W %he characters in C are grouped into the
Iollowing categories:
W Letters, Digits, Special characters and White
spaces.
Alphabets A,B,...Y,Z
A,b,...y,z
Digits 0,1,2,3,4,5,6,7,8,9
Special Symbols ~ ! # ` & * () -
, \ } | | : ; ' ~ , . ?
/
%ypes oI C Constants
C Constants
Primary Constants Secondary Constants
Integer Constant
Real Constant
Character Constant
Array
Pointer
Structure
Union
Enum etc.
Rules Ior constructing Integer Constraints
W An integer constant must have at least one digit.
W It must not have a decimal point.
W It could be either positive or negative.
W II no sign precedes an integer constant it is
assumed to be positive.
W No commas or blanks are allowed within an
integer constant.
W %he allowable range Ior integer constant is
-32768 to 32767.
Rules Ior constructing Real Constraints
W Areal constant must have at least one digit.
W It must have a decimal point.
W It could be either positive or negative.
W No commas or blanks are allowed within a real
constant.
W DeIault sign is positive.
Ex:
426.0
-32.76
483792
Rules Ior constructing Character Constraints
W %he mantissa part and the exponential part should
be separated by a letter e.
W %he mantissa part may have a positive or negative
sign.
W DeIault sign oI mantissa part is positive.
W %he exponent must have at least one digit which
must be a positive or negative integer. DeIault sign
in positive.
W Range oI real constants expresses in exponential
Iorm is -3.4e38 to 3.4e38
Ex: 3.2e-5 4.1e8
C Keywords
auto double iI static break
struct case else int static
case enum long switch char
extern near typedeI const Iloat
register union continue Iar return
unsinged deIault Ior short void
do goto signed while
C Data %ypes
C supports three classes oI data types:
1. Primary data types.
2. Derived data types.
3. User deIined data types.
Primary data types
1. Integer type:
signed : int, short int, long int.
unsigned: unsinged int, unsinged short int, unsinged
long int.
2. Character type: char, singed char, unsinged char.
3. Floating point type: Iloat, double, long double.
lze and 8ange of daLa Lypes on a 16blL
1ype S|ze(b|ts) kange
Char or slnged char 8 128 Lo 127
unslnged char 8 0 Lo 233
lnL or slnged lnL 16 32768 Lo 32767
unslnged lnL 16 0 Lo 63333
horL lnL or slnged shorL lnL 8 128 Lo 127
unslnged shorL lnL 8 0 Lo 233
Long lnL or slnged long lnL 32 2147483648 Lo 214748
unslnged long lnL 32 0 Lo 4294967293
floaL 32 34L38 Lo 34+38
double 64 17L308 Lo 17L+308
Long double 80 34L 4932 Lo 11L+4932
Declaration oI Variables
W daLaLype v1v2vn
v1,v2..vn are the names oI variables,
variables are separated by commas.
A declaration statement must end with a semicolon.
Lxample int count;
int number, total; (multiple)
double ratio;
W Derived data types
such as arrays, Iunctions, structures and pointers.
W User DeIined type declaration
1. typedeI type identiIier;
where type reIers to an existing data type and identiIier
reIers to the new name given to the data type.
Example: typedeI int units;
typedeI Iloat marks;
2. enum identiIier value1, value2, ...value n}
%he identiIier is a user deIined enumerated data type
which can be used to declare variables that can have
one oI the values enclosed with in the braces.
Declaration oI storage class
W Variables in C can have not only data type but also storage class that
provides inIormation about their location and visibility.
W %he storage class decides the portion oI the program within which
the variables are recognized.
Ex: int m;
main() Iunction1()

int i; int i;
Iloat balance; Iloat sum;
.... .....
Iunction1(); }
}
the variable m which has been declared beIore main is called global
variable
W lobal variable can be used in all the Iunctions in
the program. It need not be declared in other
Iunctions.
W A global variable is also known as an external
variable.
W %he variable i, balance and sum are called local
variables because they are declared inside Iunction.
W Local variables are visible and meaningIul only
inside the Iunction in which they are declared. %hey
are not known to other Iunctions.
Note: i has been declared in both the Iunctions, any
change in the value oI i in one Iunction does not
eIIect its value in the other.
Lorage classes
W auLo reglsLer sLaLlc and exLern
Example: auto int count; register char ch;
static int x; extern long total;
W static and external (extern) variables are automatically
initialized to zero.
W Automatic (auto) variables contain undeIined values
(known as garbage) unless they are initialized explicitly.
Storage c|ass Mean|ng
auLo Local varlable known only Lo Lhe funcLlon ln whlch lL ls
declared uefaulL ls auLo
sLaLlc Local varlable whlch exlsLs and reLalns lLs value even afLer
Lhe conLrol ls Lransferred Lo Lhe calllng funcLlon
exLern Clobal varlable known Lo all funcLlon ln Lhe flle
reglsLer Local varlable whlch ls sLored ln Lhe reglsLer
Assigning values to variables
W Iarlable_name consLanL
Lx balance 7384
W an assignment statement implies that the value oI
the variable on the leIt oI the equal sign is set equal
to the value oI the quantity on the right.
Ex: year year1;
datatype variablename constsnt;
Ex: double balance 75.84;
Initialization : the process oI giving initial values to
variables is called initialization.
p q s 0; (multiple assignments)
Program: main()

Iloat x, p;
double y, q;
Unsigned k;
int m54321;
long int n 1234567890;
x1.234567890000;
y9.87654321; output:
k54321;
pq1.0; (garbage value)
PrintI('md\n,m); m -11215 (16 bit, max store 32767)
Print('nld\n,n); n 1234567890
PrintI('x.12lI\n,x); x 1.234567880630
PrintI('xI\n,x); x 1.234568
PrintI('y.12lI\n,y); y9.876543210000
PrintI('xlI\n,x); y9.876543
PrintI('yu pI q.12lI\n,k,p,q); } k5432 p1.000000
q1.000000000000
Reading Data Irom Keyboard
ynLax
scanI('control string, &variable1,&variable2,....);
Ex: scanI('d, &number);
main()

int number;
printI('enter an integer number\n);
scanI('d, &number);
iI(number 100)
printI('your number is smaller than 100);
else
printI('your number contains more than two digits);
}
Managing Input and Output Operations
Reading a character:
getchar: Reading a single character can be done by
using the Iunction getchar.
syntax: variablename getchar();
Ex: char name;
name getchar();
Will assign the character H` to the variable name when
we press the key H on the keyboard. Since getchar is a
Iunction, it requires a set oI parentheses as shown.
#includestdio.h~
main()

char answer;
printI('would you like to know my name?\n)
printI('%ype Y Ior yes and N Ior No:);
answer getchar();
iI(answer Y` ,, answer y`)
printI('\n My name is BUSY BEE\n);
else
printI('\n you are good Ior nothing);
}
Character %est Function
nct|on 1est
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit ?
islower(c) Is c lower case letter ?
isprint(c) Is c a printable character ?
ispunct(c) Is c a punctuation mark ?
isspace(c) Is c a white space character ?
isupper(c) Is c an upper case letter ?
Writing a Character
ynLax putchar (variablename);
Where variablename is a type char variable containing a
character. %his statement displays the character contained in
the variablename at the terminal.
Ex: answer Y`;
putchar (answer);
#includestdio.h~
#includectype.h~
main()

char alphabet;
printI('enter an alphabet);
putchar(\n`); /* move to next line */
alphabet getchar();
iI(islower(alphabet))
putchar(toupper(alphabet)); /* Reverse and display */
else
putchar(tolower(alphabet)); /* Reverse and display */
Output: 1. Enter an alphabet 2. Enter an alphabet
a Q
A q
Commonly used scanf lormaL codes
ode Mean|ng
c read a slngle characLer
d read a declmal lnLeger
e read a floaLlng polnL value
f read a floaLlng polnL value
h read a shoL lnLeger
l read a declmal hexadeclmal or ocLal lnLeger
o read an ocLal lnLeger
s read a sLrlng
u read an unslgned declmal lnLeger
x read a hexadeclmal lnLeger
read a sLrlng of word(s)
Formatted output
rlnLf(conLrol sLrlng" arg1 arg2argn)
CuLpuL of lnLeger numbers
Format Output
printI('d, 9876)
printI('6d, 9876)
printI('-6d, 9876)
printI('06d, 9876)
9 8 7 6
9 8 7 6
9 8 7 6
0 0 9 8 7 6
CuLpuL of 8eal numbers
y987634
Format Output
printI('7.4I, y)
printI('7.2I, y)
printI('-7.2I, y)
printI('I, y)
PrintI('10.2e,y)
PrintI('-10.2e,y)
7 9 8 7
6 3 9 8 7 4
7 9 8 7
6 3 9 8 7 4
e + 9 8 8 0 1
0 1 8 8 e + 9
rlnLlng of a lngle CharacLer
for characLer prlnL c ls used
for sLrlng prlnL s ls used
maln()

char x A`;
char name|20| 'ANIL KUMAR UP%A;
printI('output oI characters);
printI('c\n3c\n5c\n, x,x,x);
printI('output oI strings);
printI('s\n, name);
printI('20s\n, name);
printI('20.10s\n, name);
printI('.5s\n, name);
printI('-20.10s\n, name);

Operators and Expressions


C operators can be classiIied into a number oI categories.
%hey include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operators
perator Mean|ng
+ AddlLlon or unary plus
ubLracLlon or unary mlnus
* MulLlpllcaLlon
/ ulvlslon
Modulo dlvlslon
Integer Arithmetic:
iI a14 and b4
a-b 10 ab 18 a*b 16 a/b 3 ab 2
During integer division, iI both the operands are oI the same
sign, the result is truncated towards zero. II one oI them is
negative, the direction oI truncation is implementation
dependent. 6/7 0 and -6/-70
but -6/7 may be zero or -1 (Machine dependent)
Similarly, during modulo division, the sign oI the result is
always the sign oI the Iirst operand.
-143 -2 -14 -3 -2 14-3 2
Real Arithmetic:
iI x, y and z are Iloats,
x6.0/7.0 0.857143
y1.0/3.0 0.333333
z -2.0/3.0 -0.666667
Mixed-mode Arithmetic :
When one oI the operands is real and the other is integer, the
expression is called a mixed mode arithmetic expression.
II either operand is oI the real type, then only the real
operation is perIormed and the result is always a real number.
15/10.0 1.5 15/10 1
Relational operators
perator Mean|ng
ls less Lhan
ls less Lhan or equal Lo
ls greaLer Lhan
ls greaLer Lhan or equal Lo
ls equal Lo
! ls noL equal Lo
Logical operators
Mean|ng |og|ca| AND
$$ Meanlng loglcal C8
! Meanlng loglcal nC1
Lx ab x10
Relative precedence oI the relational and logical
operators is as Iollows:
Highest !
~, ~ , ,
, !
&&
Lowest ,,
Assignment Operators
Assignment operators are used to assign the result
oI an expression to a variable.
$tatement with simple
assignment operator
$tatement with
shorthand operator
aa1 a1
aa-1 a-1
aa*(n1) a*n1
aa/(n1) a/n1
aab ab
#deIine N 100
#deIine A 2
main()

int a; output:
a A; 2
while(aN) 4
16
printI('d,a);
a * a;
}
}
Increment and Decrement operators
C allows two very useIul operators. and
%he operator ads 1 to the operand, while subtracts 1.
m; is equivalent to mm1;
--m; is equivalent to mm-1;
Ex: m5; ym;
the value oI y and m would be 6.
m5; ym
the value oI y would be 5 and m would be 6.
A preIix operator Iirst adds 1 to the operand and then the
result is assigned to the variable on leIt.
A postIix operator Iirst assigns the value to the variable on
leIt and then increments the operand.
Conditional operators
ynLax exp1? exp2 exp3
exp1 is evaluated Iirst.
WII it is nonzero(true), then the expression exp2 is
evaluated and becomes the value oI the expression .
WII exp1 is Ialse, exp3 is evaluated and its value becomes
the value oI the expression
Ex: a10; b15;
x(a~b)?a:b;
In this example, x will be assigned the value oI b.
Bitwise operators
W %hese operators are used Ior testing the bits, or
shiIting them right or leIt.
W Bitwise operators may not be applied to Iloat or
double .
perator Meaning
& Bitwise AND
, Bitwise OR
` Bitwise exclusive OR
ShiIt leIt
~~ ShiIt right
Special operators
%he comma operator:
%he comma operator can be used to link the related
expressions together.
Ex: value (x10, y5, xy);
%he sizeoI operator:
%he sizeoI is a compile time operator and, when used with an
operand, it returns the number oI bytes the operand occupies.
Ex: msizeoI(sum);
Operator Precedence
%
o
k
e
n
s

p
e
r
a
t
o
r
C
l
a
s
s
P
r
e
c
e
d
e
n
c
e
A
s
s
o
c
i
a
t
e
s
type casts unary right-to-leIt
multiplicative binary leIt-to-right
additive binary leIt-to-right
leIt, right shiIt binary leIt-to-right
relational binary leIt-to-right
equality/ineq. binary 9 leIt-to-right
bitwise and binary 8 leIt-to-right
) bitwise xor binary 7 leIt-to-right
bitwise or binary 6 leIt-to-right
logical and binary 5 leIt-to-right
logical or binary leIt-to-right
conditional ternary right-to-leIt

assignment binary right-to-leIt


sequential eval. binary leIt-to-right
Operator precedence
%
o
k
e
n
s

p
e
r
a
t
o
r
C
l
a
s
s
P
r
e
c
e
d
e
n
c
e
A
s
s
o
c
i
a
t
e
s
3,2es,
liter,ls
simple tokens primary
6
n/a
,( subscripting postIix leIt-to-right
1 Iunction call postIix leIt-to-right
direct selection postIix leIt-to-right
indirect selection postIix leIt to right
increment, decrement postfix leIt-to-right
typei3it< compound literal postIix leIt-to-right
increment, decrement prefix
5
right-to-leIt
8041 size unary right-to-leIt
= bitwise not unary right-to-leIt
logical not unary right-to-leIt
negation, plus unary right-to-leIt
address oI unary right-to-leIt

indirection
(dereference)
unary right-to-leIt
Casting Operator
Convert Irom one data type to another data type.
Ex: main()

int i10;
Iloat g50.56;
ig; /* i(int)g here Iloat value convert to integer*/
printI('d, i);
}
Output: 50
(int), (Iloat), (char), (double)
%he Decision Control structure
1he lf sLaLemenL
lf(Lhls condlLlon ls Lrue)
execuLe Lhls sLaLemenL
Lx
maln()

lnL num
prlnLf( enLer a number less Lhan 10")
scanf(d" num)
lf(num 10 )
prlnLf( less Lhan 10") (slngle sLaLemenL wlLh ln lf)

Multiple statements within iI


/* Calculation oI bonus*/
main()

int bonus, cy, yoj, yroIser;


printI('Enter current year and year oI joining);
scanI('dd, &cy, yoj);
yroIser cy-yoj;
II(yroIser ~ 3)

bonus 2500; Multiple statements


printI(' bonus RS. d, bonus); within iI
}
}
lf else sLaLemenL
/* calculation oI gross salary*/
main()

Iloat bs, gs, da, hra;


printI('Enter basic salary);
scanI('I, &bs);
iI(bs1500)

hra bs * 10/100;
da bs * 90/100;
}
else

hra 500;
da bs*98/100;
}
gs bshrada;
printI('gross salaryRs.I, gs);
}
/*nesLed lf elses */
maln()

lnL l
prlnLf(enLer elLher 1 or 2")
scanf(d" l)
lf(l1)
prlnLf(enLer 1")
else

lf(l2)
prlnLf(enLer 2")
else
prlnLf(Pl")

lorms of lf
a lf (condlLlon)
do Lhls
b lf(condlLlon)

do Lhls
and Lhls

c lf(condlLlon)
do Lhls
else
do Lhls
d lf(condlLlon)

do Lhls
and Lhls

else

do Lhls
and Lhls

e
lf(condlLlon)
do Lhls
else

lf(condlLlon)
do Lhls
else

do Lhls
and Lhls

Write a program to calculate the division obtained by the student.


main()

int m1,m2,m3,m4,m5,per;
printI('enter marks in Iive subjects);
scanI('ddddd, &m1,&m2,&m3,&m4,&m5);
per(m1m2m3m4m5)/5;
iI(per ~ 60)
printI(' Iirst division);
else

iI(per ~50)
printI(' second division);
else

iI(per ~40)
printI(' third division);
else
printI('Fail);
}
}
}
Using Logical operators
main()

int m1,m2,m3,m4,m5,per;
printI('enter marks in Iive subjects);
scanI('ddddd, &m1,&m2,&m3,&m4,&m5);
per(m1m2m3m4m5)/5;
iI(per ~ 60)
printI(' Iirst division);
iI((per ~ 50) && (per 60) )
printI(' second division);
iI((per ~ 40) && (per 50) )
printI(' third division);
iI(per 40)
printI('Fail);
}
%he Loop Control Structure
1. While Loop
2. Do-While Loop
3. For Loop
4. Nested Ior Loop
W Loops involves repeating some portion oI the
program either a speciIied number oI times or until
a particular condition is being satisIied
1.While statement
W %he While loop assists in the program where you
want to carry out an activity Ior a certain number oI
times.
Example:- calculating gross salaries oI ten people or
converting temperatures Irom centigrade to
Fahrenheit Ior 15 diIIerent cities
ynLax
Whlle (condlLlon)

LaLemenL

PRORAM EXAMPLE:
#include stdio.h~
main()

int p,n,count;
Iloat r,si;
count 1;
while (count 3)

printI("%he values oI p, n and r');


scanI('ddI, &p,&n,&r);
si p * n* r/100;
printI( "Simple interest I ' , si);
count count1;
}
}
%he condition to be tested may use the relational
operators:
Example:-
1. While (I 10)
2. While (I 10 && j 15)
3. While (j ~10 && (b 15 ,, c20)
While(i10)
ii1;
is same as
While(i10)

ii1;
}
%he Loop Control Structure
Example B:
main()

int i0;
while (i 10)
printI('d, i);
}
In the statement while( i 10),
Iirst incrementation oI I takes place, then the
comparison oI value oI I with 10 is perIormed.
%he do-While Loop
Syntax:
do

this;
and this;
and this;
and this;
}while (this condition is true);
%he do-While loop execute its statements at least once
even iI the condition Iails Ior the Iirst time.
rogram Lxample 1
#lncludesLdloh
maln()

whlle (41)
prlnLf("Pere Lhere")

W lf Lhe condlLlon falls Lhe prlnLf wlll noL be


execuLed even once
Program Example 2:
#includestdio.h~
main()

do

printI(Hello there);
}while(41);
}
W In this program the printI would be executed once,
since Iirst the body oI the loop is executed and then
the condition is tested.
For Loop
W %he Ior loop speciIies three elements about the loop in one
single line.
W Setting a loop counter to an initial value.
W %esting the loop counter to determine whether its value has
reached the number oI repetitions desired.
W Increasing the value oI loop counter each time the program
segment within the loop has been executed.
Syntax:
Ior (initialize counter; test counter; increment counter)

do this;
and this;
}
Program example: Calculate the simple interest:
#include stdio.h~
main()

int p,n,count;
Iloat r,si;
Ior (count 1; count 3; count count 1)

printI("%he values oI p, n and r');


scanI('ddI, &p,&n,&r);
si p * n* r/100;
printI( "Simple interest I ' , si);
}
}
a. main()

int i;
Ior(i1; i10;)

printI('d, i);
ii1;
}
}
W Here, the incrementation is done within the body oI the
Ior loop and not in the for statement.
b main()

int i 1;
Ior(; i10; ii1)

printI('d, i);
}
}
W Here, the initialisation is done in the declaration
statement itselI, but still the semicolon beIore the
condition necessary.
c main()

int i 1;
Ior(; i10; )

printI('d, i);
ii1;
}
}
W Here, neither the initialisation, nor the incrementation is
done in the for statement, but still the semicolon beIore
the condition necessary.
d. main()

int i;
Ior(i0; i10; )

printI('d, i);
}
}
W Here, the comparison as well as the incrementation
is done through the same statement, i++ < .
Nested Ior Loop
rogram Lxample
#includestdio.h~ output:
main() R1 c1 sum 2
R1 c2 sum 3
int r,c,sum; R2 c1 sum 3
Ior (r 1; r3; r) R2 c1 sum 4
R3 c1 sum 4
Ior (c1; c2; c) R3 c2 sum 5

sum r c;
printI('rd cd sumd, r, c, sum);
}
}
}
W Multiple initialisations in the Ior loop
Ior( i1, j2; j10; j)
%he Odd Loop :
/* LxecuLlon of a loop an unknown number of Llmes*/
#include stdio.h~
main()

char another `y`;


int num;
while(another y`)

printI(Enter a number);
scanI('d, &num;
printI('Square oI d is d', num , num * num);
printI(Do you want to enter another number y/n);
scanI('c, &another);
}
}
W In this program the while loop would keep getting executing till
the user continuous to answer y.
%he break Statement
W We want to jump out oI a loop instantly, without
waiting to get back to the conditional test. %he
keyword break allows us to do this.
W A break is usually associated with an if.
main()

int i1, j1;


while(i100)

while(j200)

iI(j150)
break;
else
printI('d\n d\n",i,j);
}
}
}
W In this program when j equals 150, break takes the control outside the
inner while only, since it is placed inside the inner while.
%he continue Statement
W In some programming situations we want to take
the control to the beginning oI the loop, bypassing
the statements inside the loop which have not yet
been executed.
W A continue is usually associated with an if.
main() output:
1 2
int i, j; 2 1
Ior (i 1; i2; i)

Ior (j 1; j2; j)

iI(ij)
continue;
printI('dd, i,j);
}
}
}
when the value oI i equals that oI j, the continue
statement takes the control to the for loop(inner) bypassing
rest oI the statements pending ececution in the for loop(inner)
%he switch Multiple-Selection Structure
W switch
UseIul when variable or expression is tested Ior multiple
values
Consists oI a series oI case labels and an optional default
case
break is (almost always) necessary
swlLch ( loteqet exptessloo )

case coostoot
1

stotemeot(s)
break
case coostoot
2

stotemeot(s)
break

defaulL
stotemeot(s)
break

W 1he lasL sLaLemenL of each case ln Lhe swlLch should


almosL always be a break
W 1he break causes program conLrol Lo [ump Lo Lhe
closlng brace of Lhe swlLch sLrucLure
W WlLhouL Lhe break Lhe code flows lnLo Lhe nexL
case 1hls ls almosL never whaL you wanL
W A swlLch sLaLemenL wlll complle wlLhouL a defaulL
case buL always conslder uslng one
swlLch ( day )

case 0 prlnLf (undayn")


break
case 1 prlnLf (Mondayn")
break
case 2 prlnLf (1uesdayn")
break
case 3 prlnLf (Wednesdayn")
break
case 4 prlnLf (1hursdayn")
break
case 3 prlnLf (lrldayn")
break
case 6 prlnLf (aLurdayn")
break
defaulL prlnLf (Lrror lnvalld dayn")
break

/* 1hls program assoclaLes a leLLer grade wlLh a


message approprlaLe Lo Lhe score */
#lnclude sLdloh
lnL maln ( )

char grade
prlnLf (LnLer your currenL leLLer graden)
grade geLchar ( )
swlLch (grade)

case (a)
case (A)
prlnLf (Cood !ob!n)
case (b)
case (8)
prlnLf (reLLy goodn)
case (c)
case (C)
prlnLf (8eLLer geL Lo workn)
case (d)
case (u)
prlnLf (?ou are ln Lroublen)
defaulL
prlnLf (?ou are falllng!!n)
/* Lnd of swlLchcase sLrucLure */
/* Lnd of molo program
/* 1he followlng resulLs are produced when Lhe user
enLers an A as lnpuL Lo Lhe program prompL */
Cood !ob!
reLLy good
8eLLer geL Lo work
?ou are ln Lrouble
?ou are falllng!
W 1he problems wlLh Lhe prevlous program can be
correcLed by use of Lhe teok sLaLemenL
W lL can be used ln elLher a repeLlLlon sLrucLure or a
selecLlon sLrucLure Lo break ouL of (LhaL ls Lo exlL
from) Lhe sLrucLure
W 1he synLax ls
break
W 1he followlng program ls Lhe prevlous one wlLh Lhe
addlLlon of Lhe teok sLaLemenLs
#lnclude sLdloh
maln ( )

lnL l2
swlLch(l)

case 1
prlnLf(l am ln case 1")
break
case 2
prlnLf(l am ln case 2")
break
case 3
prlnLf(l am ln case 3")
break
defaulL
prlnLf(l am ln defaulL")

tpt I am |n case 2
Functions
What is a Function?
Function is a selI contained block oI statements that
perIorm a coherent task oI some kind.
Every C program can be a thought oI the collection oI
Iunctions.
main( ) is also a Iunction.
W Any c program contains at least one Iunction.
W II a program contains only one Iunction, it must be
main().
W %here is no limit on the number oI Iunctions that might
be present in a c program.
W Each Iunction in a program is called in the sequence
speciIied by the Iunction call in main().
1ypes of luncLlons
W Llbrary funcLlons
W 1hese are Lhe ln bullL funcLlons of 'C' llbrary
W 1hese are already deflned ln header flles
eg prlnLf( ) ls a funcLlon whlch ls used Lo prlnL aL
ouLpuL lL ls deflned ln 'sLdloh' flle
-user deflned funcLlons
W rogrammer can creaLe Lhelr own funcLlon ln C Lo
perform speclflc Lask
Dser def|ned fnct|ons
#lncludesLdloh
maln()

message()
prlnLf(cry and you sLop Lhe monoLony")

message()

prlnLf(smlle and Lhe world smlles wlLh you")

tpt sm||e and the wor|d sm||es w|th yo


cry and yo stop the monotony
Declaration oI many Iunctions
main( )
engg()
printI('I am in main);
poly( ); printI( 'I am in engineering );
engg( ); }
agri( ); agri()
}
poly( ) printI( 'I am inagri );
}
printI('I am in polytechnic);
}
maln()

prlnLf(l am ln maln")
|ta|y()
prlnLf( lam flnally back ln maln") otpt
l am ln maln
Ita|y() I am |n |ta|y
I am |n braz||
pr|ntf("I am |n |ta|y") I am |n argent|na
braz||() I am back |n |ta|y
pr|ntf("I am back |n |ta|y") lam flnally back ln maln

braz||()

pr|ntf("I am |n braz||")
argent|na()

argent|na()

pr|ntf("I am |n argent|na ")

Summarization
- C rogram ls a collecLlon of one or more funcLlons
- A funcLlon geLs called when lLs name ls followed by
a semlcolon
eg maln( )

fun( )

fun( )

LaLemenL1 sLaLemenL2 sLaLemenL3

W A Iunction is deIined when Iunction name is


Iollowed by a pair oI braces in which one or more
statements present.
fun( )

sLaLemenL1
sLaLemenL2
sLaLemenL3

W Any funcLlon can be called by any oLher funcLlon


maln( )

prlnLf(ll am ln maln")
fun( )

fun( )

rlnLf(l am ln fun")
maln( )

1h|s w||| rn |n |nf|n|ty


A funcLlon can be called by number of Llmes
eg
maln( )

prlnLf(l am ln maln")
fun( )
fun( )
fun( )

fun( )

prlnLf(l am ln fun")

A funcLlon can call lLself lL ls called as a ''recurslon"
eg
maln ( )

prlnLf(l am ln maln")
maln( )

W A funcLlon can be called from anoLher funcLlon buL


can noL be deflned ln anoLher funcLlon lL should be
deflned ouLslde of Lhe maln
W 1he order ln whlch Lhe funcLlons are deflned ln a program and
Lhe order ln whlch Lhey geL called need noL necessarlly be
same
maln()

message1()
message2()

message2()

prlnLf(smlle and Lhe world smlles wlLh you")

message1()

prlnLf(cry and you sLop Lhe monoLony")

Jhy se fnct|ons?
W Writing Iunctions avoids rewriting oI the same code
again and again in the program.
W Using a Iunction it becomes easier to write program
to keep track oI what they are doing.
Passing values between Iunctions
1he values LhaL we pass Lo Lhe funcLlon called as funcLlon argumenLs
eg
maln( )

lnL l10 [12 k20


calsum(l[k)

calsum(lnL x lnL y lnL z)

rlnLf(um ls d" (x+y+z))

CuLpuL 42
| [ k are acta| argments
x y z are forma| argments
Returning a value
W %he keyword return`` to used to return value Irom Iunction which
is present in the parenthesis oI return.
W executing return statement it immediately transIers control back to
the main program.
main( )
int a 30, j 14;
int k;
k addin(a, j);
PrintI('d, k);

lnL addln(lnL x lnL y) ouLpuL 43

lnL z
z (x + y) +1
reLurn(z)

W %here is no restriction on the number oI return statements that


may be present in a Iunction.
W Also, the return statement need not always be present at the
end oI the called Iunction.
Ex:
Iun()

char ch;
printI('enter any alphabet);
scanI('c,&ch);
iI(ch~65 && ch90)
return (ch);
else
return (ch32);
}
W In this Iunction diIIerent return statements will be executed
depending on whether ch is capital or not.
W Whenever the control returns Irom the Iunction some
value is deIinitely returned. It should be accepted in the
calling program.
e.g. int sum;
sum calsum(a,b,c);
here the value returned by calsum must be of type int.
$ome valid return statements.
return a; /*a is a variable name */
return (23);
return (15.32);
return (v``);
return;
W II you are not returning any value Irom a Iunction they it should
be declared as void. (void is a keyword).
e.g. void display( ) display is not returning any value.
W A Iunction can return only one value at a time. %hus,
the Iollowing statements are invalid.
return(a,b);
return(x,12);
W Any C Iunction by deIault returns an integer value.
More speciIically, whenever a call is made to a
Iunction, the compiler assumes that this Iunction
would return value oI type int.
ueclarlng luncLlons
W 8equlres proLoLype funcLlon lLself
a roLoLype (before funcLlon lLself)
1ells compller
1 number Lype of argumenLs passed ln
2 1ype of value reLurned
Lg
lnL maxlmum (lnL lnL)
or
lnL maxlmum (lnL a lnL b)
/* a b are lgnored by Lhe compller */
W luncLlon lLself
lormaL Lype funcLlon_name (parameLer llsL)
arameLer llsL Lype and name
MusL reLurn a value of speclfled Lype unless
Lype ls vold
MusL be declared before lL ls used
W luncLlon call
MusL lnclude approprlaLe argumenLs
#lnclude sLdloh
lnL maxlmum (lnL lnL) nct|on prototype
lnL maxlmum (lnL a lnL b)

lf (a b)
reLurn a
else
reLurn b

vold maln ()
lnL x y z
prlnLf (LnLer 2 lnLergers )
scanf (d d" x y)
z maxlmum(xy)
prlnLf(n1he maxlmum ls dn"z)

Call by value and call by Reference


An introduction to Pointers:
Ex: int i 3;
%his declaration tells the c compiler to:
1. Reserve space in memory to hold the integer value.
2. Associate the name I with this memory location.
3. Store the value 3 at this location.
i location name
value at location
6485 location number
W %he computer has selected memory location 6485 as
the place to store the value 3. the location number
6485 is not Iixed Ior value 3.
3
We can print this address number through the Iollowing
program:
main()

int i 3;
PrintI('address oI iu, &i);
printI('value oI i d, i);
}
Output: address oI i 6485
value oI i 3;
&` used in this statement is C`s address oI` operator. %he
expression &i returns the address oI the variable i.
W %he other pointer operator available in C is *`
called value at address` operator. It gives the value
stored at a particular address.
W %he value at address` operator is also called
indirection` operator.
Ex: main()
int i3;
PrintI('address oI iu, &i);
printI('value oI i d, i);
printI('value oI i d,*(& i)); }
utput: address of i 685
value of i ;
value of i ;
W the printing the value oI *(&i) is same as printing
the value oI i.
W the expression &i gives the address oI the variable i.
this address can be collected in a variable, by
saying,
j&i;
W j is not an ordinary variable like any other integer
variable. It is a variable which contains the address
oI other variable.
i j (j value is is address)
6485 3276
3
6483
Lx maln()

lnL l3 ouLpuL
lnL *[ address oI i 6485
[l address oI i 6485
prlnLf(address oI iu, &i); address oI j 3276
prlnLf(address oI iu, j); value oI j 6485
prlnLf(address oI ju, &j); value oI i 3
printI('value oI j u, j); value oI i 3
printI('value oI i d, i); value oI i 3
printI('value oI i d, *(&i));
printI('value oI i d, *j);
}
8ack Lo luncLlon calls
W Arguments can generally be passed to Iunction in
one oI the two ways:
1. sending the values oI the arguments
2. sending the addresses oI the arguments
W In the Iirst method the value oI each oI actual
arguments in the calling Iunction is copied into
corresponding Iormal arguments oI the called
Iunction.
W With this method the changes made to the Iormal
arguments in the called Iunction have no eIIect on
the values oI actual arguments in the calling
Iunction
/* interchange the values */
main()

int x50, y70;
interchange(x,y);
printI('xd yd,x,y);
}
interchange(x1,y1) output:
int x1,y1; x1 70 y1 50
x 50 y 70
int z1;
z1x1;
x1y1;
y1z1;
printI('x1d y1d,x1,y1);
}
W In second method (call by reIerence) the address oI
actual arguments in the calling Iunction are copied
into Iormal arguments oI the called Iunction.
W %his means that using these addresses we would
have an access to the actual arguments and here we
would be able to manipulate them.
main()

int x50, y70;
interchange(&x,&y);
printI('xd yd,x,y);
}
output:
interchange(x1,y1) *x70 *y30
int *x1,*y1; x70 y30

int z1;
z1*x1;
*x1*y1;
*y1z1;
printI('*xd *yd,x1,y1);
}
8ecurslon
W A Iunction is called recursive` iI a statement with in the
body oI a Iunction calls the same Iunction.
W Sometimes called circular definition, recursion is thus the
process oI deIining something in terms oI itselI.
W int Iact(int n) ouLpuL
int x,y; Enter the integer whose Iactorial value you want
iI(n0) 3
return 1;
xn-1; %he Iactorial value is 6
yIact(x);
return n*y; }
void main()
int x;
printI('\nEnter the integer whose Iactorial value you want ');
scanI('d,&x);
printI('\n%he Iactorial value is:-d,Iact(x)); }