Lec-4 C Programming
Transcript of Lec-4 C Programming
-
8/19/2019 Lec-4 C Programming
1/66
1Dept. of CSE, IIT KGP
FunctionsFunctions
CS10001:CS10001: Programming & Data StructuresProgramming & Data Structures
Pallab DasguptaPallab Dasgupta
Professor, Dept. of ComputerProfessor, Dept. of ComputerSc. & Engg.,Sc. & Engg.,
Indian Institute ofIndian Institute ofTechnology KharagpurTechnology Kharagpur
-
8/19/2019 Lec-4 C Programming
2/66
2Dept. of CSE, IIT KGP
IntrouctionIntrouction
• FunctionFunction – ! se"f#containe program segment t$at carries out some! se"f#containe program segment t$at carries out some
specific, %e""#efine tas.specific, %e""#efine tas.
• Some properties:Some properties: – E'er( C program consists of one or more functions.E'er( C program consists of one or more functions.
• )ne of t$ese functions must *e ca""e +)ne of t$ese functions must *e ca""e + main main..
• E-ecution of t$e program a"%a(s *egins *( carr(ing out t$eE-ecution of t$e program a"%a(s *egins *( carr(ing out t$e
instructions in +instructions in + main main..
– ! function %i"" carr( out its intene action %$ene'er it is! function %i"" carr( out its intene action %$ene'er it is
called called oror invoked invoked ..
-
8/19/2019 Lec-4 C Programming
3/66
3Dept. of CSE, IIT KGP
– In genera", a function %i"" process information t$at is passeIn genera", a function %i"" process information t$at is passe
to it from t$e ca""ing portion of t$e program, an returns ato it from t$e ca""ing portion of t$e program, an returns a
sing"e 'a"ue.sing"e 'a"ue.
• Information is passe to t$e function 'ia specia" ientifiersInformation is passe to t$e function 'ia specia" ientifiersca""eca""e argumentsarguments oror parameters parameters..
• T$e 'a"ue is returne *( t$e +T$e 'a"ue is returne *( t$e +returnreturn statement. statement.
– Some functions ma( not return an(t$ing.Some functions ma( not return an(t$ing.
• eturn ata t(pe specifie as +eturn ata t(pe specifie as +void void ..
-
8/19/2019 Lec-4 C Programming
4/66
4Dept. of CSE, IIT KGP
/inc"ue stio.$/inc"ue stio.$
int factoria" 2int m3int factoria" 2int m3
44
int i, temp516int i, temp516
for 2i516 i5m6 i773for 2i516 i5m6 i773
temp 5 temp 8 i6temp 5 temp 8 i6
return 2temp36return 2temp36
99
main23main23
44
int n6int n6
for 2n516 n5106 n773for 2n516 n5106 n773
printf 2+; 5
-
8/19/2019 Lec-4 C Programming
5/66
5Dept. of CSE, IIT KGP
A$( FunctionsBA$( FunctionsB
• FunctionsFunctions
– !""o%s one to e'e"op a program in a mou"ar fas$ion!""o%s one to e'e"op a program in a mou"ar fas$ion..
• Di'ie#an#conuer approac$.Di'ie#an#conuer approac$.
–!"" 'aria*"es ec"are insie functions are "oca" 'aria*"es!"" 'aria*"es ec"are insie functions are "oca" 'aria*"es
.
.
• Kno%n on"( in function efine.Kno%n on"( in function efine.
• T$ere are e-ceptions 2to *e iscusse "ater3.T$ere are e-ceptions 2to *e iscusse "ater3.
– ParametersParameters
• Communicate information *et%een functions.Communicate information *et%een functions.
• T$e( a"so *ecome "oca" 'aria*"es.T$e( a"so *ecome "oca" 'aria*"es.
-
8/19/2019 Lec-4 C Programming
6/66
6Dept. of CSE, IIT KGP
• enefitsenefits – Di'ie an conuer Di'ie an conuer
• anagea*"e program e'e"opment.anagea*"e program e'e"opment.
• Construct a program from sma"" pieces orConstruct a program from sma"" pieces or
components.components.
– Soft%are reusa*i"it(Soft%are reusa*i"it(
• se e-isting functions as *ui"ing *"ocs for ne%se e-isting functions as *ui"ing *"ocs for ne%
programs.programs.
• !*straction: $ie interna" etai"s 2"i*rar( functions3.!*straction: $ie interna" etai"s 2"i*rar( functions3.
-
8/19/2019 Lec-4 C Programming
7/66
7Dept. of CSE, IIT KGP
Defining a FunctionDefining a Function
• ! function efinition $as t%o parts:! function efinition $as t%o parts:
– T$e first "ine.T$e first "ine.
– T$e *o( of t$e function.T$e *o( of t$e function.
return-value-type function-namereturn-value-type function-name (( parameter-list parameter-list ))
{{
declarations and statementsdeclarations and statements
}}
-
8/19/2019 Lec-4 C Programming
8/66
8Dept. of CSE, IIT KGP
• T$e first "ine contains t$e return#'a"ue#t(pe, t$e functionT$e first "ine contains t$e return#'a"ue#t(pe, t$e functionname, an optiona""( a set of comma#separate argumentsname, an optiona""( a set of comma#separate arguments
enc"ose in parent$eses.enc"ose in parent$eses.
– Eac$ argument $as an associate t(pe ec"aration.Eac$ argument $as an associate t(pe ec"aration.
– T$e arguments are ca""eT$e arguments are ca""e formal argumentsformal arguments or or formalformal
parameters parameters..
• E-amp"e:E-amp"e:
int gc 2int !, int 3int gc 2int !, int 3
• T$e argument ata t(pes can a"so *e ec"are on t$e ne-t "ine:T$e argument ata t(pes can a"so *e ec"are on t$e ne-t "ine:
int gc 2!, 3int gc 2!, 3
4 int !, 6 ##### 94 int !, 6 ##### 9
-
8/19/2019 Lec-4 C Programming
9/66
9Dept. of CSE, IIT KGP
• T$e *o( of t$e function is actua""( a compoun statementT$e *o( of t$e function is actua""( a compoun statementt$at efines t$e action to *e taen *( t$e functiont$at efines t$e action to *e taen *( t$e function..
int gc 2int !, int 3int gc 2int !, int 3
44
int temp6int temp6%$i"e 22 !3 ;5 03 4%$i"e 22 !3 ;5 03 4
temp 5 !6temp 5 !6
5 !6 5 !6
! 5 temp6! 5 temp6
99
return 2!36return 2!36
99
)D)D
-
8/19/2019 Lec-4 C Programming
10/66
10Dept. of CSE, IIT KGP
• A$en a function is ca""e from some ot$er function, t$eA$en a function is ca""e from some ot$er function, t$e
corresponing arguments in t$e function ca"" are ca""ecorresponing arguments in t$e function ca"" are ca""e
actual argumentsactual arguments oror actual actual parameters parameters..
– T$e forma" an actua" arguments must matc$ in t$eirT$e forma" an actua" arguments must matc$ in t$eir
ata t(pes.ata t(pes.
– T$e notion of positiona" parameters is importantT$e notion of positiona" parameters is important
• Point to note:Point to note:
– T$e ientifiers use as forma" arguments are +"oca".T$e ientifiers use as forma" arguments are +"oca".
• Hot recognie outsie t$e function.Hot recognie outsie t$e function.
• Hames of forma" an actua" arguments ma( iffer.Hames of forma" an actua" arguments ma( iffer.
-
8/19/2019 Lec-4 C Programming
11/66
11Dept. of CSE, IIT KGP
/inc"ue stio.$/inc"ue stio.$ J8 Compute t$e GCD of four num*ers 8J J8 Compute t$e GCD of four num*ers 8J
main23main23
44
int n1, n=, n>, n, resu"t6int n1, n=, n>, n, resu"t6
scanf 2+ , &n1, &n=, &n>, &n36scanf 2+ , &n1, &n=, &n>, &n36
resu"t 5 gc 2 gc 2n1, n=3, gc 2n>, n3 36resu"t 5 gc 2 gc 2n1, n=3, gc 2n>, n3 36
printf 2+T$e GCD of , , an is
-
8/19/2019 Lec-4 C Programming
12/66
12Dept. of CSE, IIT KGP
Function Hot eturning !n( La"ueFunction Hot eturning !n( La"ue
• E-amp"eE-amp"e: ! function %$ic$ prints if a num*er is i'isi*"e *(: ! function %$ic$ prints if a num*er is i'isi*"e *(M or not.M or not.
'oi i'M 2int n3'oi i'M 2int n3
44
if 22n M3 55 03if 22n M3 55 03
printf 2+ is i'isi*"e *( M, n36printf 2+ is i'isi*"e *( M, n36
e"see"se
printf 2+ is not i'isi*"e *( M, n36printf 2+ is not i'isi*"e *( M, n36
return6return6
99
OPTIONAL
-
8/19/2019 Lec-4 C Programming
13/66
13Dept. of CSE, IIT KGP
• eturning contro"eturning contro"
– If not$ing returneIf not$ing returne
• returnreturn;; • or, unti" reac$es rig$t *raceor, unti" reac$es rig$t *race
– If somet$ing returneIf somet$ing returne •
returnreturn
expressionexpression;;
-
8/19/2019 Lec-4 C Programming
14/66
14Dept. of CSE, IIT KGP
Some PointsSome Points
• ! function cannot *e efine %it$in anot$er function.! function cannot *e efine %it$in anot$er function. – !"" function efinitions must *e isNoint!"" function efinitions must *e isNoint..
• Heste function ca""s are a""o%e.Heste function ca""s are a""o%e.
– ! ca""s , ca""s C, C ca""s D, etc.! ca""s , ca""s C, C ca""s D, etc. – T$e function ca""e "ast %i"" *e t$e first to return.T$e function ca""e "ast %i"" *e t$e first to return.
• ! function can a"so ca"" itse"f, eit$er irect"( or in a c(c"e.! function can a"so ca"" itse"f, eit$er irect"( or in a c(c"e.
– ! ca""s , ca""s C, C ca""s *ac !.! ca""s , ca""s C, C ca""s *ac !.
– Ca""eCa""e recursive call recursive call or or recursionrecursion..
-
8/19/2019 Lec-4 C Programming
15/66
15Dept. of CSE, IIT KGP
E-amp"e::E-amp"e:: main main ca""sca""s ncrncr,, ncrncr ca""sca""s factfact
/inc"ue stio.$/inc"ue stio.$
int ncr 2int n, int r36int ncr 2int n, int r36
int fact 2int n36int fact 2int n36
main23main23
44
int i, m, n, sum506int i, m, n, sum506
scanf 2+ , &m, &n36scanf 2+ , &m, &n36
for 2i516 i5m6 i75=3for 2i516 i5m6 i75=3
sum 5 sum 7 ncr 2n, i36sum 5 sum 7 ncr 2n, i36
printf 2+esu"t:
-
8/19/2019 Lec-4 C Programming
16/66
16
Laria*"eLaria*"e
ScopeScope
Output:
--------------
A = 3
A = 2
A = 1
/inc"ue stio.$
int !6
'oi main23
4 ! 5 16
m(Proc236
printf 2 O! 5
-
8/19/2019 Lec-4 C Programming
17/66
17Dept. of CSE, IIT KGP
at$ i*rar( Functionsat$ i*rar( Functions
• at$ "i*rar( functionsat$ "i*rar( functions – perform common mat$ematica" ca"cu"ationsperform common mat$ematica" ca"cu"ations
#include #include
• Format for ca""ing functionsFormat for ca""ing functionsFunctionName (argument);FunctionName (argument);
• If mu"tip"e arguments, use comma#separate "istIf mu"tip"e arguments, use comma#separate "ist
printf ("%f", sqrt(!!.!)); printf ("%f", sqrt(!!.!));
• Ca""s functionCa""s function sqrtsqrt, %$ic$ returns t$e suare root of its, %$ic$ returns t$e suare root of its
argument.argument.• !"" mat$ functions return ata t(pe!"" mat$ functions return ata t(pe doubledouble..
– !rguments ma( *e constants, 'aria*"es, or e-pressions!rguments ma( *e constants, 'aria*"es, or e-pressions ..
-
8/19/2019 Lec-4 C Programming
18/66
18Dept. of CSE, IIT KGP
at$ i*rar( Functionsat$ i*rar( Functions
double acosdouble !"double acosdouble !" # Compute arc cosine of !.# Compute arc cosine of !.
double asindouble !"double asindouble !" # Compute arc sine of !.# Compute arc sine of !.
double atandouble !"double atandouble !" # Compute arc tangent of !.# Compute arc tangent of !.
double atan$double y, double !"double atan$double y, double !" # Compute arc tangent of y%!.# Compute arc tangent of y%!.
double cosdouble !"double cosdouble !" # Compute cosine of angle in radians.# Compute cosine of angle in radians.
double coshdouble !"double coshdouble !" # Compute the hyperbolic cosine of !.# Compute the hyperbolic cosine of !.
double sindouble !"double sindouble !" # Compute sine of angle in radians.# Compute sine of angle in radians.double sinhdouble !"double sinhdouble !" # Compute the hyperbolic sine of !.# Compute the hyperbolic sine of !.
double tandouble !"double tandouble !" # Compute tangent of angle in radians.# Compute tangent of angle in radians.
double tanhdouble !"double tanhdouble !" # Compute the hyperbolic tangent of !.# Compute the hyperbolic tangent of !.
-
8/19/2019 Lec-4 C Programming
19/66
19Dept. of CSE, IIT KGP
at$ i*rar( Functionsat$ i*rar( Functions
double ceildouble !"double ceildouble !" # et smallest integral 'alue that e!ceeds !.# et smallest integral 'alue that e!ceeds !.
double floordouble !"double floordouble !" # et largest integral 'alue less than !.# et largest integral 'alue less than !.
double e!pdouble !"double e!pdouble !" # Compute e!ponential of !.# Compute e!ponential of !.
double fabs double ! "double fabs double ! " # Compute absolute 'alue of !.# Compute absolute 'alue of !.
double logdouble !"double logdouble !" # Compute log to the base e of !.# Compute log to the base e of !.
double log() double ! "double log() double ! " # Compute log to the base () of !.# Compute log to the base () of !.
double po* double !, double y"double po* double !, double y" # Compute ! raised to the po*er y.# Compute ! raised to the po*er y.
double s+rtdouble !"double s+rtdouble !" # Compute the s+uare root of !.# Compute the s+uare root of !.
-
8/19/2019 Lec-4 C Programming
20/66
20Dept. of CSE, IIT KGP
Function Protot(pesFunction Protot(pes
• sua""(, a function is efine *efore it is ca""e.sua""(, a function is efine *efore it is ca""e.– main() main() is t$e "ast function in t$e program.is t$e "ast function in t$e program.
– Eas( for t$e compi"er to ientif( function efinitions in aEas( for t$e compi"er to ientif( function efinitions in a
sing"e scan t$roug$ t$e fi"e.sing"e scan t$roug$ t$e fi"e.
• Qo%e'er, man( programmers prefer a top#o%n approac$,Qo%e'er, man( programmers prefer a top#o%n approac$,
%$ere t$e functions fo""o%%$ere t$e functions fo""o% main(). main().
– ust *e some %a( to te"" t$e compi"er.ust *e some %a( to te"" t$e compi"er.
– Function protot(pes are use for t$is purpose.Function protot(pes are use for t$is purpose.
• )n"( neee if function efinition comes after use.)n"( neee if function efinition comes after use.
-
8/19/2019 Lec-4 C Programming
21/66
21Dept. of CSE, IIT KGP
– Function protot(pes are usua""( %ritten at t$e *eginning ofFunction protot(pes are usua""( %ritten at t$e *eginning ofa program, a$ea of an( functions 2inc"uinga program, a$ea of an( functions 2inc"uing main()main()33..
– E-amp"es:E-amp"es:
int gc 2int !, int 36int gc 2int !, int 36
'oi i'M 2int num*er36'oi i'M 2int num*er36
• Hote t$e semico"on at t$e en of t$e "ine.Hote t$e semico"on at t$e en of t$e "ine.
• T$e argument names can *e ifferent6 *ut it is a gooT$e argument names can *e ifferent6 *ut it is a goo
practice to use t$e same names as in t$e function efinition.practice to use t$e same names as in t$e function efinition.
-
8/19/2019 Lec-4 C Programming
22/66
22Dept. of CSE, IIT KGP
Qeaer Fi"esQeaer Fi"es
• Qeaer fi"esQeaer fi"es – Contain function protot(pes for "i*rar( functions.Contain function protot(pes for "i*rar( functions.
– ,, , etc, etc
– oa %it$:oa %it$: #include #include
– E-amp"eE-amp"e::
#include #include
• Custom $eaer fi"esCustom $eaer fi"es – Create fi"e2s3 %it$ function efinitions.Create fi"e2s3 %it$ function efinitions.
– Sa'e asSa'e asfilename.hfilename.h
2sa(3.2sa(3.
– oa in ot$er fi"es %it$oa in ot$er fi"es %it$ #include "filename.h"#include "filename.h"
– euse functions.euse functions.
-
8/19/2019 Lec-4 C Programming
23/66
23Dept. of CSE, IIT KGP
Parameter passing: *( La"ue an *( eferenceParameter passing: *( La"ue an *( eference
• se %$en in'oing functions.se %$en in'oing functions.
• Ca"" *( 'a"ueCa"" *( 'a"ue
– Passes t$ePasses t$e valuevalue of t$e argument to t$e function.of t$e argument to t$e function.
– E-ecution of t$e function oes not affect t$e origina".E-ecution of t$e function oes not affect t$e origina". – se %$en function oes not nee to moif( argument.se %$en function oes not nee to moif( argument.
• !'ois accienta" c$anges.!'ois accienta" c$anges.
• Ca"" *( referenceCa"" *( reference
– Passes t$ePasses t$e referencereference to t$e origina" argument.to t$e origina" argument. – E-ecution of t$e function ma( affect t$e origina".E-ecution of t$e function ma( affect t$e origina".
– Hot irect"( supporte in C RHot irect"( supporte in C R can be effected by using pointerscan be effected by using pointers
++C supports on"( ca"" *( 'a"ueC supports on"( ca"" *( 'a"ue
-
8/19/2019 Lec-4 C Programming
24/66
24Dept. of CSE, IIT KGP
E-amp"e:E-amp"e:anom Hum*er Generationanom Hum*er Generation
•
rand rand functionfunction – Protot(pe efine inProtot(pe efine in
– eturns OranomO num*er *et%eeneturns OranomO num*er *et%een !! anan $N&'$$N&'$
i rand();i rand();
– PseuoranomPseuoranom
– Preset seuence of OranomO num*ersPreset seuence of OranomO num*ers
• Same seuence for e'er( function ca""Same seuence for e'er( function ca""
• Sca"ingSca"ing
– To get a ranom num*er *et%eenTo get a ranom num*er *et%een ** anan nn
* + (rand() % n )* + (rand() % n ) – To simu"ate t$e ro"" of a ice:To simu"ate t$e ro"" of a ice:
* + (rand() % )* + (rand() % )
-
8/19/2019 Lec-4 C Programming
25/66
25Dept. of CSE, IIT KGP
anom Hum*er Generation: Cont.anom Hum*er Generation: Cont.
• srand srand functionfunction – Protot(pe efine inProtot(pe efine in ..
– Taes an integer see, an ranomies t$e ranomTaes an integer see, an ranomies t$e ranom
num*er generator.num*er generator.
srand (seed);srand (seed);
-
8/19/2019 Lec-4 C Programming
26/66
26Dept. of CSE, IIT KGP
1 J8 ! programming e-amp"e
= anomiing ie#ro""ing program 8J
> /inc"ue st"i*.$
/inc"ue stio.$
? int main23M 4
int i6
U unsigne see610
11 printf2 OEnter see: O 361= scanf2 OuO, &see 36
1> sran2 see 361
1 for 2 i 5 16 i 5 106 i77 3 4
1? printf2 O10 O, 1 7 2 ran23 ? 3 36
1M
1 if 2 i 55 0 3
1U printf2 O 9
-
8/19/2019 Lec-4 C Programming
27/66
27Dept. of CSE, IIT KGP
Program )utputProgram )utput
-nter seed /0 1 2 * * * 3 1
-nter seed 0
* 2 1 * * 2
-nter seed 0 * 2 1 * * 2
-
8/19/2019 Lec-4 C Programming
28/66
28Dept. of CSE, IIT KGP
/efine: acro efinition/efine: acro efinition
• Preprocessor irecti'e in t$e fo""o%ing formPreprocessor irecti'e in t$e fo""o%ing form:: /efine string1 string=/efine string1 string=
– ep"aces string1 *( string= %$ere'er it occurs *eforeep"aces string1 *( string= %$ere'er it occurs *eforecompi"ation. For e-amp"e,compi"ation. For e-amp"e,
/efine PI >.11U=?/efine PI >.11U=?
-
8/19/2019 Lec-4 C Programming
29/66
29Dept. of CSE, IIT KGP
/efine: acro efinition/efine: acro efinition
/inc"ue stio.$/inc"ue stio.$
/efine PI >.11U=?/efine PI >.11U=?
main23main23
44
f"oat r5.0,area6f"oat r5.0,area6
area5PI8r8r6area5PI8r8r6
99
/inc"ue stio.$/inc"ue stio.$
main23main23
44
f"oat r5.0,area6f"oat r5.0,area6
area5area5>.11U=?>.11U=?8r8r68r8r6
99
-
8/19/2019 Lec-4 C Programming
30/66
30Dept. of CSE, IIT KGP
/efine %it$ arguments/efine %it$ arguments
• #define#define statement ma( *e use %it$ arguments.statement ma( *e use %it$ arguments.
– E-amp"e:E-amp"e: /efine sr2-3 -8-/efine sr2-3 -8-
– Qo% %i"" macro su*stitution *e carrie outBQo% %i"" macro su*stitution *e carrie outB
r 5 sr2a3 7 sr2>036r 5 sr2a3 7 sr2>036 r 5 a8a 7 >08>06 r 5 a8a 7 >08>06
r 5 sr2a7*36r 5 sr2a7*36 r 5 a7*8a7*6 r 5 a7*8a7*6
– T$e macro efinition s$ou" $a'e *een %ritten as:T$e macro efinition s$ou" $a'e *een %ritten as:
/efine sr2-3 2-382-3/efine sr2-3 2-382-3
r 5 2a7*382a7*36r 5 2a7*382a7*36
-/0-/0
-
8/19/2019 Lec-4 C Programming
31/66
31Dept. of CSE, IIT KGP
ecursionecursion
• ! process *( %$ic$ a function ca""s itse"f repeate"(.! process *( %$ic$ a function ca""s itse"f repeate"(. – Eit$er irect"(.Eit$er irect"(.
• V ca""s V.V ca""s V.
– )r c(c"ica""( in a c$ain.)r c(c"ica""( in a c$ain.
• V ca""s , an ca""s V.V ca""s , an ca""s V.
• se for repetiti'e computations in %$ic$ eac$ action is statese for repetiti'e computations in %$ic$ eac$ action is state
in terms of a pre'ious resu"t.in terms of a pre'ious resu"t.
fact2n3 5 n 8 fact 2n#13fact2n3 5 n 8 fact 2n#13
-
8/19/2019 Lec-4 C Programming
32/66
32Dept. of CSE, IIT KGP
Cont.Cont.
• For a pro*"em to *e %ritten in recursi'e form, t%o conitionsFor a pro*"em to *e %ritten in recursi'e form, t%o conitionsare to *e satisfie:are to *e satisfie:
– It s$ou" *e possi*"e to e-press t$e pro*"em in recursi'eIt s$ou" *e possi*"e to e-press t$e pro*"em in recursi'e
form.form.
– T$e pro*"em statement must inc"ue a stopping conitionT$e pro*"em statement must inc"ue a stopping conition
fact2n3 5 1, if n 5 0fact2n3 5 1, if n 5 0
5 n 8 fact2n#13, if n 05 n 8 fact2n#13, if n 0
-
8/19/2019 Lec-4 C Programming
33/66
33Dept. of CSE, IIT KGP
• E-amp"es:E-amp"es:
– Factoria":Factoria":fact203 5 1fact203 5 1
fact2n3 5 n 8 fact2n#13, if n 0fact2n3 5 n 8 fact2n#13, if n 0
– GCD:GCD:gc 2m, m3 5 mgc 2m, m3 5 m
gc 2m, n3 5 gc 2mn, n3, if m ngc 2m, n3 5 gc 2mn, n3, if m n
gc 2m, n3 5 gc 2n, nm3, if m ngc 2m, n3 5 gc 2n, nm3, if m n
– Fi*onacci series 21,1,=,>,,,1>,=1,@.3Fi*onacci series 21,1,=,>,,,1>,=1,@.3fi* 203 5 1fi* 203 5 1
fi* 213 5 1fi* 213 5 1
fi* 2n3 5 fi* 2n#13 7 fi* 2n#=3, if n 1fi* 2n3 5 fi* 2n#13 7 fi* 2n#=3, if n 1
-
8/19/2019 Lec-4 C Programming
34/66
34Dept. of CSE, IIT KGP
E-amp"e 1 :: Factoria"E-amp"e 1 :: Factoria"
"ong int fact 2n3"ong int fact 2n3
int n6int n6
44
if 2n 5 5 13if 2n 5 5 13
return 2136return 2136
e"see"se
return 2n 8 fact2n#1336return 2n 8 fact2n#1336
99
-
8/19/2019 Lec-4 C Programming
35/66
35Dept. of CSE, IIT KGP
E-amp"e 1 :: Factoria" E-ecutionE-amp"e 1 :: Factoria" E-ecution
if if (( 1 1 ("1 1 ("return ("2return ("2else return ( 3else return ( 3fact)""2fact)""2
fact4"fact4"
if if 44 1 1 ("1 1 ("return ("2return ("2else return else return 4 34 3fact5"fact5""2"2 if if 55 1 1 ("1 1 ("
return ("2return ("2else return else return 5 35 3fact$"fact$""2"2 if if $$ 1 1 ("1 1 ("
return ("2return ("2else return else return $ 3$ 3
fact("fact(""2"2
11
==
??
==
long int fact n"long int fact n"
int n2int n266 if n 1 1 ("if n 1 1 ("return ("2return ("2 else return n 3else return n 3factn7(""2factn7(""2
88
-
8/19/2019 Lec-4 C Programming
36/66
36Dept. of CSE, IIT KGP
E-amp"e = :: Fi*onacci num*er E-amp"e = :: Fi*onacci num*er
• Fi*onacci num*er f2n3 can *e efine as:Fi*onacci num*er f2n3 can *e efine as: f203 5 0f203 5 0
f213 5 1f213 5 1
f2n3 5 f2n#13 7 f2n#=3, if n 1f2n3 5 f2n#13 7 f2n#=3, if n 1
– T$e successi'e Fi*onacci num*ers are:T$e successi'e Fi*onacci num*ers are:
0, 1, 1, =, >, , , 1>, =1, @..0, 1, 1, =, >, , , 1>, =1, @..
• Function efinition:Function efinition:
int f 2int n3int f 2int n3
44
if 2n =3 return 2n36if 2n =3 return 2n36
e"se return 2f2n#13 7 f2n#=336e"se return 2f2n#13 7 f2n#=336
99
-
8/19/2019 Lec-4 C Programming
37/66
37Dept. of CSE, IIT KGP
Tracing E-ecutionTracing E-ecution
• Qo% man( times is t$eQo% man( times is t$e
function ca""e %$enfunction ca""e %$en
e'a"uating f23 Be'a"uating f23 B
• Inefficienc(:Inefficienc(:
– Same t$ing is computeSame t$ing is compute
se'era" times.se'era" times.
f23
f2>3 f2=3
f213f2=3 f203f213
f213 f203
ca""e U times
-
8/19/2019 Lec-4 C Programming
38/66
38Dept. of CSE, IIT KGP
Hota*"e PointHota*"e Point
• E'er( recursi'e program can a"so *e %ritten %it$out recursionE'er( recursi'e program can a"so *e %ritten %it$out recursion
• ecursion is use for programming con'enience, not forecursion is use for programming con'enience, not for
performance en$ancementperformance en$ancement
• Sometimes, if t$e function *eing compute $as a niceSometimes, if t$e function *eing compute $as a nice
recurrence form, t$en a recursi'e coe ma( *e more reaa*"erecurrence form, t$en a recursi'e coe ma( *e more reaa*"e
-
8/19/2019 Lec-4 C Programming
39/66
39Dept. of CSE, IIT KGP
E-amp"e > :: To%ers of Qanoi Pro*"emE-amp"e > :: To%ers of Qanoi Pro*"em
>
=1
LEFT CENTER RIGHT
-
8/19/2019 Lec-4 C Programming
40/66
40Dept. of CSE, IIT KGP
• T$e pro*"em statement:T$e pro*"em statement:
– Initia""( a"" t$e iss are stace on t$e EFT po"e.Initia""( a"" t$e iss are stace on t$e EFT po"e.
– euire to transfer a"" t$e iss to t$e IGQT po"e.euire to transfer a"" t$e iss to t$e IGQT po"e.• )n"( one is can *e mo'e at a time.)n"( one is can *e mo'e at a time.
• ! "arger is cannot *e p"ace on a sma""er is! "arger is cannot *e p"ace on a sma""er is..
– CEHTE po"e is use for temporar( storage of iss.CEHTE po"e is use for temporar( storage of iss.
-
8/19/2019 Lec-4 C Programming
41/66
41Dept. of CSE, IIT KGP
• ecursi'e statement of t$e genera" pro*"em of n iss.ecursi'e statement of t$e genera" pro*"em of n iss.
– Step 1:Step 1:
• o'e t$e top 2n#13 iss from EFT to CEHTE.o'e t$e top 2n#13 iss from EFT to CEHTE.
– Step =:Step =:
• o'e t$e "argest is from EFT to IGQT.o'e t$e "argest is from EFT to IGQT.
– Step >:Step >: • o'e t$e 2n#13 iss from CEHTE to IGQT.o'e t$e 2n#13 iss from CEHTE to IGQT.
-
8/19/2019 Lec-4 C Programming
42/66
42Dept. of CSE, IIT KGP
/inc"ue stio.$/inc"ue stio.$
'oi transfer 2int n, c$ar from, c$ar to, c$ar temp36'oi transfer 2int n, c$ar from, c$ar to, c$ar temp36
main23main23
44
int n6 J8 Hum*er of iss 8Jint n6 J8 Hum*er of iss 8J
scanf 2+, &n36scanf 2+, &n36
transfer 2n, WX, WX, WCX36transfer 2n, WX, WX, WCX36
99
'oi transfer 2int n, c$ar from, c$ar to, c$ar temp3'oi transfer 2int n, c$ar from, c$ar to, c$ar temp3
44
if 2n 03 4if 2n 03 4
transfer 2n#1, from, temp, to36transfer 2n#1, from, temp, to36
printf 2+o'e is from c to c
-
8/19/2019 Lec-4 C Programming
43/66
43Dept. of CSE, IIT KGP
-
8/19/2019 Lec-4 C Programming
44/66
44Dept. of CSE, IIT KGP
-
8/19/2019 Lec-4 C Programming
45/66
45Dept. of CSE, IIT KGP
ecursion 's. Iterationecursion 's. Iteration
• epetitionepetition – Iteration: e-p"icit "oopIteration: e-p"icit "oop
– ecursion: repeate function ca""secursion: repeate function ca""s
• TerminationTermination
– Iteration: "oop conition fai"sIteration: "oop conition fai"s
– ecursion: *ase case recognieecursion: *ase case recognie
• ot$ can $a'e infinite "oopsot$ can $a'e infinite "oops
• a"ancea"ance
– C$oice *et%een performance 2iteration3 an gooC$oice *et%een performance 2iteration3 an goo
soft%are engineering 2recursion3.soft%are engineering 2recursion3.
-
8/19/2019 Lec-4 C Programming
46/66
46Dept. of CSE, IIT KGP
Qo% are function ca""s imp"ementeBQo% are function ca""s imp"ementeB
• T$e fo""o%ing app"ies in genera", %it$ minor 'ariations t$at areT$e fo""o%ing app"ies in genera", %it$ minor 'ariations t$at are
imp"ementation epenent.imp"ementation epenent.
– T$e s(stem maintains a stac in memor(.T$e s(stem maintains a stac in memor(.
• Stac is a "ast#in first#out structure.Stac is a "ast#in first#out structure.
• T%o operations on stac, pus$ an pop.T%o operations on stac, pus$ an pop.
– A$ene'er t$ere is a function ca"", t$e acti'ation recor getsA$ene'er t$ere is a function ca"", t$e acti'ation recor gets
pus$e into t$e stac.pus$e into t$e stac.
• !cti'ation recor consists of t$e return aress in t$e ca""ing!cti'ation recor consists of t$e return aress in t$e ca""ing
program, t$e return 'a"ue from t$e function, an t$e "oca"program, t$e return 'a"ue from t$e function, an t$e "oca"'aria*"es insie t$e function.'aria*"es insie t$e function.
-
8/19/2019 Lec-4 C Programming
47/66
47Dept. of CSE, IIT KGP
main23
4 @@..
- 5 gc 2a, *36
@@..
9
int gc 2int -, int (3
4
@@..
@@..
return 2resu"t36
9
eturn !r
eturn La"ue
oca"
Laria*"es
!"#$! %&'' A"!$ %&'' A"!$ $!$*
+ T A C ,
A%-.&-#*
$!%#$/
-
8/19/2019 Lec-4 C Programming
48/66
48Dept. of CSE, IIT KGP
main23
4
@@..
- 5 ncr 2a, *36
@@..9
int ncr 2int n, int r3
4
return 2fact2n3J fact2r3Jfact2n#r336
9
L1, L1, !1
!"#$! %&'' C&'' "&% *%$ $!$*
int fact 2int n34
@@@
return 2resu"t36
9
> times
L1, L1, !1
"&% $!$*
L1, L1, !1
L=, L=, !=
C&'' *%$
> times
-
8/19/2019 Lec-4 C Programming
49/66
49Dept. of CSE, IIT KGP
A$at $appens for recursi'e ca""sBA$at $appens for recursi'e ca""sB
• A$at %e $a'e seen @.A$at %e $a'e seen @.
– !cti'ation recor gets pus$e into t$e stac %$en a function!cti'ation recor gets pus$e into t$e stac %$en a function
ca"" is mae.ca"" is mae.
– !cti'ation recor is poppe off t$e stac %$en t$e function!cti'ation recor is poppe off t$e stac %$en t$e function
returns.returns.
• In recursion, a function ca""s itse"f.In recursion, a function ca""s itse"f.
– Se'era" function ca""s going on, %it$ none of t$e functionSe'era" function ca""s going on, %it$ none of t$e function
ca""s returning *ac.ca""s returning *ac.
• !cti'ation recors are pus$e onto t$e stac continuous"(.!cti'ation recors are pus$e onto t$e stac continuous"(.
• arge stac space reuire.arge stac space reuire.
-
8/19/2019 Lec-4 C Programming
50/66
50Dept. of CSE, IIT KGP
– !cti'ation recors eep popping off, %$en t$e termination!cti'ation recors eep popping off, %$en t$e termination
conition of recursion is reac$e.conition of recursion is reac$e.
• Ae s$a"" i""ustrate t$e process *( an e-amp"e of computingAe s$a"" i""ustrate t$e process *( an e-amp"e of computing
factoria".factoria".
– !cti'ation recor "oos "ie:!cti'ation recor "oos "ie:
eturn !r
eturn La"ue
oca"
Laria*"es
-
8/19/2019 Lec-4 C Programming
51/66
51Dept. of CSE, IIT KGP
E-amp"e:: main23 ca""s fact2>3E-amp"e:: main23 ca""s fact2>3
int fact 2n3
int n6
4
if 2n 5 5 03
return 2136
e"se
return 2n 8 fact2n#1336
9
main23
4
int n6
n 5 >6
printf 2+
-
8/19/2019 Lec-4 C Programming
52/66
-
8/19/2019 Lec-4 C Programming
53/66
53Dept. of CSE, IIT KGP
Do ourse"f Do ourse"f
• Trace t$e acti'ation recors for t$e fo""o%ing 'ersion of Fi*onacciTrace t$e acti'ation recors for t$e fo""o%ing 'ersion of Fi*onacci
seuence.seuence.
#include #include int f (int n)int f (int n)44
int a, ;int a, ; if (n < 1) return (n);if (n < 1) return (n); else 4else 4 a f(n5*);a f(n5*); f(n51); f(n51); return (a+); 6return (a+); 666
main() 4 main() 4 printf(7Fi(2) is %d 8n9, f(2)); printf(7Fi(2) is %d 8n9, f(2));66
eturn !r
2eit$er main,
or V, or 3
eturn La"ue
oca"
Laria*"es2n, a, *3
&-*
-
8/19/2019 Lec-4 C Programming
54/66
54Dept. of CSE, IIT KGP
Storage C"ass of Laria*"esStorage C"ass of Laria*"es
-
8/19/2019 Lec-4 C Programming
55/66
55Dept. of CSE, IIT KGP
A$at is Storage C"assBA$at is Storage C"assB
•It refers to t$e permanence of a 'aria*"e, an itsIt refers to t$e permanence of a 'aria*"e, an its scopescope %it$in a%it$in aprogram.program.
• Four storage c"ass specifications in C:Four storage c"ass specifications in C:
– !utomatic!utomatic:: autoauto
– E-terna"E-terna" :: e:terne:tern – StaticStatic :: staticstatic
– egisteregister :: registerregister
-
8/19/2019 Lec-4 C Programming
56/66
56Dept. of CSE, IIT KGP
!utomatic Laria*"es!utomatic Laria*"es
•T$ese are a"%a(s ec"are %it$in a function an are "oca" to t$eT$ese are a"%a(s ec"are %it$in a function an are "oca" to t$efunction in %$ic$ t$e( are ec"are.function in %$ic$ t$e( are ec"are.
– Scope is confine to t$at function.Scope is confine to t$at function.
• T$is is t$e efau"t storage c"ass specification.T$is is t$e efau"t storage c"ass specification.
– !"" 'aria*"es are consiere as!"" 'aria*"es are consiere as autoauto un"ess e-p"icit"(un"ess e-p"icit"(specifie ot$er%ise.specifie ot$er%ise.
– T$e e(%orT$e e(%or autoauto is optiona".is optiona".
– !n automatic 'aria*"e oes not retain its 'a"ue once contro" is!n automatic 'aria*"e oes not retain its 'a"ue once contro" is
transferre out of its efining function.transferre out of its efining function.
-
8/19/2019 Lec-4 C Programming
57/66
57Dept. of CSE, IIT KGP
#include #include
int factorial(int m)int factorial(int m)
44
auto int i;auto int i;
auto int temp*;auto int temp*;
for (i*; i
-
8/19/2019 Lec-4 C Programming
58/66
58Dept. of CSE, IIT KGP
Static Laria*"esStatic Laria*"es
• Static 'aria*"es are efine %it$in ini'iua" functions an $a'eStatic 'aria*"es are efine %it$in ini'iua" functions an $a'et$e same scope as automatic 'aria*"es.t$e same scope as automatic 'aria*"es.
• n"ie automatic 'aria*"es, static 'aria*"es retain t$eir 'a"uesn"ie automatic 'aria*"es, static 'aria*"es retain t$eir 'a"ues
t$roug$out t$e "ife of t$e program.t$roug$out t$e "ife of t$e program.
– If a function is e-ite an re#entere at a "ater time, t$e staticIf a function is e-ite an re#entere at a "ater time, t$e static'aria*"es efine %it$in t$at function %i"" retain t$eir pre'ious'aria*"es efine %it$in t$at function %i"" retain t$eir pre'ious
'a"ues.'a"ues.
– Initia" 'a"ues can *e inc"ue in t$e static 'aria*"e ec"aration.Initia" 'a"ues can *e inc"ue in t$e static 'aria*"e ec"aration.
• Ai"" *e initia"ie on"( once.Ai"" *e initia"ie on"( once.• !n e-amp"e of using static 'aria*"e:!n e-amp"e of using static 'aria*"e:
– Count num*er of times a function is ca""e.Count num*er of times a function is ca""e.
-
8/19/2019 Lec-4 C Programming
59/66
59Dept. of CSE, IIT KGP
#include #include
int factorial (int n)int factorial (int n)
44
static int count!;static int count!;
count++;count++;
printf (7n%d, count%d 8n9, n, count); printf (7n%d, count%d 8n9, n, count);
if (n !) return *;if (n !) return *;
else return (n factorial(n5*));else return (n factorial(n5*));
66
main() main()44
int i;int i;
printf (7=alue is %d 8n9, factorial(i)); printf (7=alue is %d 8n9, factorial(i));
66
EV!PE 1
-
8/19/2019 Lec-4 C Programming
60/66
60Dept. of CSE, IIT KGP
• Program output:Program output: n, count*n, count*
n, count1n, count1
n2, count3n2, count3
n3, count2n3, count2
n1, countn1, count
n*, countn*, count
n!, count0n!, count0
=alue is 01! =alue is 01!
-
8/19/2019 Lec-4 C Programming
61/66
61Dept. of CSE, IIT KGP
#include #include
int fi (int n)int fi (int n)
44
static int count!;static int count!;
count++;count++;
printf (7n%d, count%d 8n9, n, count); printf (7n%d, count%d 8n9, n, count);
if (n < 1) return n;if (n < 1) return n;
else return (fi(n5*) + fi(n51));else return (fi(n5*) + fi(n51));
66
main() main()44
int i2;int i2;
printf (7=alue is %d 8n9, fi(i)); printf (7=alue is %d 8n9, fi(i));
66
EV!PE =
-
8/19/2019 Lec-4 C Programming
62/66
62Dept. of CSE, IIT KGP
• Program output:Program output: n2, count*n2, count* n3, count1n3, count1
n1, count3n1, count3
n*, count2n*, count2
n!, countn!, count
n*, countn*, count
n1, count0n1, count0
n*, count/n*, count/
n!, countn!, count =alue is 3 ?!,*,*,1,3,,/,@.A =alue is 3 ?!,*,*,1,3,,/,@.A
f23
f2>3 f2=3
f213f2=3 f203f213
f213 f203
-
8/19/2019 Lec-4 C Programming
63/66
63Dept. of CSE, IIT KGP
egister Laria*"esegister Laria*"es
• T$ese 'aria*"es are store in $ig$#spee registers %it$in t$e CP.T$ese 'aria*"es are store in $ig$#spee registers %it$in t$e CP.
– Common"( use 'aria*"es ma( *e ec"are as registerCommon"( use 'aria*"es ma( *e ec"are as register
'aria*"es.'aria*"es.
– esu"ts in increase in e-ecution spee.esu"ts in increase in e-ecution spee.
– T$e a""ocation is one *( t$e compi"er.T$e a""ocation is one *( t$e compi"er.
-
8/19/2019 Lec-4 C Programming
64/66
64Dept. of CSE, IIT KGP
E-terna" Laria*"esE-terna" Laria*"es
• T$e( are not confine to sing"e functions.T$e( are not confine to sing"e functions.
• T$eir scope e-tens from t$e point of efinition t$roug$ t$eT$eir scope e-tens from t$e point of efinition t$roug$ t$e
remainer of t$e program.remainer of t$e program.
– T$e( ma( span more t$an one functions.T$e( ma( span more t$an one functions.
– !"so ca""e g"o*a" 'aria*"es!"so ca""e g"o*a" 'aria*"es..
• !"ternate %a( of ec"aring g"o*a" 'aria*"es.!"ternate %a( of ec"aring g"o*a" 'aria*"es.
– Dec"are t$em outsie t$e function, at t$e *eginningDec"are t$em outsie t$e function, at t$e *eginning..
-
8/19/2019 Lec-4 C Programming
65/66
65Dept. of CSE, IIT KGP
#include #include
int count!; B CDE$D =$G$D- Bint count!; B CDE$D =$G$D- B
int factorial (int n)int factorial (int n)
44
count++;count++;
printf (7n%d, count%d 8n9, n, count); printf (7n%d, count%d 8n9, n, count);
if (n !) return *;if (n !) return *;
else return (n factorial(n5*));else return (n factorial(n5*));
66
main() 4 main() 4
int i;int i;
printf (7=alue is %d 8n9, factorial(i)); printf (7=alue is %d 8n9, factorial(i));
printf (7Hount is %d 8n9, count); printf (7Hount is %d 8n9, count);
66
-
8/19/2019 Lec-4 C Programming
66/66
• Program output:Program output: n, count*n, count* n, count1n, count1
n2, count3n2, count3
n3, count2n3, count2
n1, countn1, count
n*, countn*, count
n!, count0n!, count0
=alue is 01! =alue is 01!
Hount is 0Hount is 0