78
Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur

Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

  • Upload
    others

  • View
    14

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Functions

Prof.IndranilSenGupta

Dept.ofComputerScience&Engg.IndianInstituteofTechnology

Kharagpur

Page 2: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 2

Introduction

• Function– Aself-containedprogramsegmentthatcarriesoutsomespecific,well-definedtask.

• Someproperties:– EveryCprogramconsistsofoneormorefunctions.

• Oneofthesefunctionsmustbecalled“main”.• Executionoftheprogramalwaysbeginsbycarryingouttheinstructions in“main”.

– Afunctionwillcarryoutitsintendedactionwheneveritiscalled orinvoked.

Autumn Semester2019

Page 3: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 3

– Ingeneral,afunctionwillprocessinformationthatispassedtoitfromthecallingportionoftheprogram,andreturnasinglevalue.• Informationispassedtothefunctionviaspecialidentifierscalledarguments orparameters.

• Thevalueisreturnedbythe“return”statement.

– Somefunctionmaynotreturnanything.• Returndatatypespecifiedas“void”.

Autumn Semester2019

Page 4: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 4

#include <stdio.h>

int factorial (int m)

{

int i, temp=1;for (i=1; i<=m; i++)

temp = temp * i;

return (temp);

}

int main(){

int n;

for (n=1; n<=10; n++)

printf (ʺ%d! = %d \nʺ,n, factorial (n));

return 0;

}

Output:1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Autumn Semester2019

Page 5: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 5

#include <stdio.h>

int factorial (int m)

{

int i, temp=1;for (i=1; i<=m; i++)

temp = temp * i;

return (temp);

}

int main(){

int n;

for (n=11; n<=20; n++)

printf (ʺ%d! = %d \nʺ,n, factorial (n));

return 0;

}

Output:11! = 39916800 12! = 479001600 13! = 1932053504 14! = 1278945280 15! = 2004310016 16! = 2004189184 17! = -288522240 18! = -898433024 19! = 109641728 20! = -2102132736

Autumn Semester2019

Page 6: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 6

#include <stdio.h>

long int factorial (int m)

{

int i; long int temp=1;for (i=1; i<=m; i++)

temp = temp * i;

return (temp);

}

int main(){

int n;

for (n=11; n<=20; n++)

printf (ʺ%d! = %ld \nʺ,n, factorial (n));

return 0;

}

Output:11! = 39916800 12! = 479001600 13! = 6227020800 14! = 87178291200 15! = 1307674368000 16! = 20922789888000 17! = 355687428096000 18! = 6402373705728000 19! = 121645100408832000 20! = 2432902008176640000

Autumn Semester2019

Page 7: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 7

WhyFunctions?

• Functions– Allowsonetodevelopaprograminamodularfashion.

• Divide-and-conquerapproach.

– Allvariablesdeclaredinsidefunctionsarelocalvariables.• Knownonlyinfunctiondefined.• Thereareexceptions(tobediscussedlater).

– Parameters• Communicateinformationbetweenfunctions.• Theyalsobecomelocalvariables.

Autumn Semester2019

Page 8: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 8

• Benefits– Divideandconquer

• Manageableprogramdevelopment.• Constructaprogramfromsmallpiecesorcomponents.

– Softwarereusability• Useexistingfunctionsasbuildingblocksfornewprograms.• Abstraction:hideinternaldetails(libraryfunctions).

Autumn Semester2019

Page 9: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 9

DefiningaFunction

• Afunctiondefinitionhastwoparts:– Thefirstline.– Thebodyofthefunction.

return-value-typefunction-name(parameter-list ){declarationsandstatements

}

Autumn Semester2019

Page 10: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 10

• Thefirstlinecontainsthereturn-value-type, thefunctionname,andoptionallyasetofcomma-separatedargumentsenclosedinparentheses.– Eachargumenthasanassociatedtypedeclaration.– Theargumentsarecalledformalarguments orformalparameters.

• Example:int gcd (int A, int B)

• Theargumentdatatypescanalsobedeclaredonthenextline:int gcd (A, B)int A, B;

Autumn Semester2019

Page 11: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 11

• Thebodyofthefunctionisactuallyacompoundstatementthatdefinestheactiontobetakenbythefunction.

int gcd (int A, int B){

int temp;while ((B % A) != 0) {temp = B % A;B = A;A = temp;

}return A;

}

BODY

Autumn Semester2019

Page 12: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 12

• Whenafunctioniscalledfromsomeotherfunction,thecorrespondingargumentsinthefunctioncallarecalledactualarguments oractualparameters.– Theformalandactualargumentsmustmatchintheirdatatypes.

• Pointtonote:– Theidentifiersusedasformalargumentsare“local”.

• Notrecognizedoutsidethefunction.• Namesofformalandactualargumentsmaydiffer.

Autumn Semester2019

Page 13: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 13

#include <stdio.h>/* Compute the GCD of four numbers */

int main()

{int n1, n2, n3, n4, result;

scanf (ʺ%d %d %d %dʺ, &n1, &n2, &n3, &n4);result = gcd ( gcd (n1, n2), gcd (n3, n4) );

printf (ʺThe GCD of %d, %d, %d and %d is %d \nʺ,n1, n2, n3, n4, result);

return 0;

}

Autumn Semester2019

Page 14: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 14

FunctionNotReturningAnyValue

• Example:Afunctionwhichprintsifanumberifdivisibleby7ornot.

void div7 (int n)

{

if ((n % 7) == 0)

printf (ʺ%d is divisible by 7ʺ, n);else

printf (ʺ%d is not divisible by 7ʺ, n);

return;

}OPTIONAL

Autumn Semester2019

Page 15: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 15

• Returningcontrol– Ifnothingreturned

• return;

• or,untilreachesrightbrace

– Ifsomethingreturned• return expression;

Autumn Semester2019

Page 16: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 16

FunctionPrototypes

• Usually,afunction isdefinedbeforeitiscalled.– main() isthelastfunctionintheprogram.– Easyforthecompilertoidentifyfunctiondefinitionsinasingle

scanthroughthefile.

• However,manyprogrammerspreferatop-downapproach,wherethefunctionsfollowmain().– Mustbesomewaytotellthecompiler.– Functionprototypesareusedforthispurpose.

• Onlyneedediffunctiondefinitioncomesafteruse.

Autumn Semester2019

Page 17: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 17

– Functionprototypesareusuallywrittenatthebeginningofaprogram,aheadofanyfunctions(includingmain()).

– Examples:int gcd (int A, int B);

void div7 (int number);

• Notethesemicolonattheendoftheline.• Theargumentnamescanbedifferent;butitisagoodpracticetousethesamenamesasinthefunctiondefinition.

Autumn Semester2019

Page 18: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 18

SomePoints

• Afunctioncannotbedefinedwithinanotherfunction.– Allfunctiondefinitionsmustbedisjoint.

• Nestedfunctioncallsareallowed.– AcallsB,BcallsC,CcallsD,etc.– Thefunctioncalledlastwillbethefirsttoreturn.

• Afunctioncanalsocallitself,eitherdirectlyorinacycle.– AcallsA– AcallsB,BcallsC,CcallsbackA.– Calledrecursivecall orrecursion.

Autumn Semester2019

Page 19: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Example::main callsncr,ncr callsfact#include <stdio.h>

int ncr (int n, int r);int fact (int n);

void main(){

int i, m, n, sum=0;scanf (ʺ%d %dʺ, &m, &n);

for (i=1; i<=m; i+=2)sum = sum + ncr(n,i);

printf (ʺResult: %d \nʺ, sum);

}

int ncr (int n, int r){

return (fact(n) / fact(r) / fact(n-r));

}

int fact (int n){

int i, temp=1;for (i=1; i<=n; i++)

temp *= i;return (temp);

}

19Programming and DataStructureAutumn Semester2019

Page 20: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 20

#include<stdio.h>intA;voidmain()

{ A=1;myProc();printf("A=%d\n",A);

}

voidmyProc(){intA=2;

while(A==2){intA=3;printf("A=%d\n",A);break;

}printf("A=%d\n",A);

}

VariableScope

Output:

A = 3

A = 2

A = 1

Autumn Semester2019

Page 21: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 21

MathLibraryFunctions

• Mathlibraryfunctions– performcommonmathematicalcalculations

#include <math.h>

• FormatforcallingfunctionsFunctionName (argument);• Ifmultiplearguments,usecomma-separatedlist

printf (ʺ%fʺ, sqrt(900.0));

• Callsfunctionsqrt,whichreturnsthesquarerootofitsargument.• Allmathfunctionsreturndatatypedouble.

– Argumentsmaybeconstants,variables,orexpressions.

Autumn Semester2019

Page 22: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

doubleacos(doublex) – Computearccosineofx.doubleasin(doublex) – Computearcsineofx.doubleatan(doublex) – Computearctangentofx.doubleatan2(doubley,doublex) – Computearctangentofy/x.

doubleceil(doublex) – Getsmallestintegralvaluethatexceedsx.doublefloor(doublex) – Getlargestintegralvaluelessthanx.doublecos(doublex) – Computecosineofangleinradians.doublecosh(doublex) – Computethehyperboliccosineofx.

doublesin(doublex) – Computesineofangleinradians.doublesinh(doublex) – Computethehyperbolicsineofx.doubletan(doublex) – Computetangentofangleinradians.doubletanh(doublex) – Computethehyperbolictangentofx.

doubleexp(doublex) – Computeexponentialofx.doublefabs(doublex) – Computeabsolutevalueofx.doublelog(doublex) – Computelogtothebaseeofx.doublelog10(doublex) – Computelogtothebase10ofx.

doublepow(doublex,doubley) – Computexraisedtothepowery.doublesqrt(doublex) – Computethesquarerootofx.

Programming and DataStructure 22

MathLibraryFunctions

Autumn Semester2019

Page 23: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Anexample#include <stdio.h>

#include <math.h>

int main()

{

double value, result;

float a, b;

value = 2345.6; a = 23.5;

result = sqrt(value);

b = pow(23.5,4);

printf (ʺ\nresult = %f, b = %fʺ, result, b);

return 0;

}

Programming and DataStructure 23

Must be compiled as:

gcc examp.c -lm

Linkmathlibrary

Autumn Semester2019

Page 24: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 24

HeaderFiles

• Headerfiles– Containfunctionprototypesforlibraryfunctions– <stdlib.h> ,<math.h> ,etc.– Loadwith: #include <filename>

– Example:#include <math.h>

• Customheaderfiles– Createfile(s)withfunctiondefinitions.– Saveasfilename.h (say).– Loadinotherfileswith#include ̋ filename.hʺ– Reusefunctions.

Autumn Semester2019

Page 25: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 25

CallingFunctions:CallbyValueandCallbyReference

• Usedwheninvokingfunctions.• Callbyvalue

– Copyofargumentpassedtofunction.– Changesinfunctiondonotaffectoriginal.– Usewhenfunctiondoesnotneedtomodifyargument.

• Avoidsaccidentalchanges.• Callbyreference.

– Passesthereferencetotheoriginalargument.– Executionofthefunctionmayaffecttheoriginal.– NotdirectlysupportedinC– canbeeffectedusingpointers.

Csupportsonly“callbyvalue”

Autumn Semester2019

Page 26: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 26

Example: RandomNumberGeneration

• rand function– Prototypedefinedin<stdlib.h>– Returns"random"numberbetween0 andRAND_MAX

i = rand();

– Pseudorandom• Presetsequenceof"random"numbers• Samesequenceforeveryfunctioncall

• Scaling– Togetarandomnumberbetween1 andn

1 + (rand() % n)

– Tosimulatetherollofadice:1 + (rand() % 6)

Autumn Semester2019

Page 27: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 27

RandomNumberGeneration:Contd.

• srand function– Prototypedefinedin <stdlib.h>

– Takesanintegerseed,andrandomizestherandomnumbergenerator.

srand (seed);

Autumn Semester2019

Page 28: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Autumn Semester2019 Programming and DataStructure 28

#include <stdio.h>#include <stdlib.h>

int main()

{

int i;

unsigned seed;

printf (ʺEnter seed: ʺ);

scanf (ʺ%uʺ, &seed);

srand (seed);

for (i = 1; i <= 10; i++) {

printf(ʺ%10d ʺ, 1 + (rand() % 6));

if (i % 5 == 0)

printf (ʺ\nʺ);

}

return 0;

}

Aprogrammingexample.Randomizingdierollingprogram.

Page 29: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

ProgramOutput

Enter seed: 8672 4 6 1 61 1 3 6 2

Enter seed: 676 1 4 6 21 6 1 6 4

Enter seed: 676 1 4 6 21 6 1 6 4

Page 30: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 30

#define:Macrodefinition

• Preprocessordirectivesarehandledbythepreprocessor,beforetheactualcompilation

• Preprocessordirectiveinthefollowingform:#define string1 string2

– Replacesstring1bystring2whereveritoccursbeforecompilation.

– Forexample,#define PI 3.1415926#define discr b*b-4*a*c

Autumn Semester2019

Page 31: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 31

#define:Macrodefinition

#include <stdio.h>

#define PI 3.1415926

void main()

{

float r=4.0, area;

area = PI*r*r;

}

#include <stdio.h>

void main()

{

float r=4.0, area;

area = 3.1415926*r*r;

}

Autumn Semester2019

This replacement is done by the preprocessor

Page 32: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 32

#definewitharguments

• #define statementmaybeusedwitharguments.– Example:#define sqr(x) x*x– Howmacrosubstitutionwillbecarriedout?

r = sqr(a) + sqr(30); è r = a*a + 30*30;r = sqr(a+b); è r = a+b*a+b;

– Themacrodefinitionshouldhavebeenwrittenas:#define sqr(x) (x)*(x)

r = (a+b)*(a+b);

WRONG?

Autumn Semester2019

Page 33: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 33

Recursion

• Aprocessbywhichafunctioncallsitselfrepeatedly.– Eitherdirectly.

• XcallsX.

– Orcyclically inachain.• XcallsY,andYcallsX.

• Usedforrepetitivecomputations inwhicheachactionisstatedintermsofapreviousresult.

fact(n) = n * fact (n-1)

Autumn Semester2019

Page 34: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 34

Contd.

• Foraproblemtobewritteninrecursiveform,twoconditionsaretobesatisfied:– Itshouldbepossibletoexpresstheprobleminrecursiveform.

– Theproblemstatementmustincludeastoppingconditionfact(n) = 1, if n = 0

= n * fact(n-1), if n > 0

Autumn Semester2019

Page 35: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 35

• Examples:– Factorial:

fact(0) = 1fact(n) = n * fact(n-1), if n > 0

– GCD:gcd (m, m) = mgcd (m, n) = gcd (m%n, n), if m > ngcd (m, n) = gcd (n, n%m), if m < n

– Fibonacci series(0,1,1,2,3,5,8,13,….)fib (0) = 0fib (1) = 1fib (n) = fib (n-1) + fib (n-2), if n > 1

Autumn Semester2019

Page 36: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Example1::Factorial

Autumn Semester2019 Programming and DataStructure 36

long int fact (n)int n;{

if (n == 0)return (1);

elsereturn (n * fact(n-1));

}

Page 37: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 37

• Mechanismofexecution– Whenarecursiveprogramisexecuted,therecursivefunctioncallsarenotexecutedimmediately.• Theyarekeptaside(onastack)untilthestoppingconditionisencountered.

• Thefunctioncallsarethenexecutedinreverseorder.

Autumn Semester2019

Page 38: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 38

Example::Calculatingfact(4)

– First,thefunctioncallswillbeprocessed:fact(4) = 4 * fact(3)

fact(3) = 3 * fact(2)fact(2) = 2 * fact(1)

fact(1) = 1 * fact(0)

– Theactualvaluesreturninthereverseorder:fact(0) = 1

fact(1) = 1 * 1 = 1

fact(2) = 2 * 1 = 2

fact(3) = 3 * 2 = 6fact(4) = 4 * 6 = 24

Autumn Semester2019

Page 39: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 39

Example2::GCD

int gcd (m, n)int m, n;{

if(m == n)return m;

else if(n==0)return m;

elsereturn gcd (n, m%n);

}

Autumn Semester2019

Page 40: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 40

Example2::GCDint gcd (m, n)int m, n;{

printf( "\n Within gcd(): m = %d, n = %d", m, n );

if(m == n)return m;

else if(n==0)return m;

elsereturn gcd (n, m%n);

}

Autumn Semester2019

int main(){

int a, b;scanf(“%d %d”, &a, &b);printf( "\n a = %d, b = %d, gcd = %d", a, b,

gcd(a,b) );}

Page 41: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Example2:GCD

Autumn Semester2019 Programming and DataStructure 41

Inputs: 100, 30

Within gcd(): m = 100, n = 30Within gcd(): m = 30, n = 10Within gcd(): m = 10, n = 0a = 100, b = 30, gcd = 10

Inputs: 100, 29

Within gcd(): m = 100, n = 29Within gcd(): m = 29, n = 13Within gcd(): m = 13, n = 3Within gcd(): m = 3, n = 1Within gcd(): m = 1, n = 0 a = 100, b = 29, gcd = 1 Inputs: 30, 100

Within gcd(): m = 30, n = 100Within gcd(): m = 100, n = 30Within gcd(): m = 30, n = 10Within gcd(): m = 10, n = 0 a = 30, b = 100, gcd = 10

Page 42: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 42

Example3::Fibonaccinumber

• Fibonaccinumberf(n)canbedefinedas:f(0) = 0f(1) = 1f(n) = f(n-1) + f(n-2), if n > 1

– ThesuccessiveFibonacci numbersare:0,1,1,2,3,5,8,13,21,…..

• Functiondefinition:int f (int n){

if (n < 2) return (n);else return (f(n-1) + f(n-2));

}

Autumn Semester2019

Page 43: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 43

TracingExecution

• Howmanytimesthefunctioniscalledwhenevaluatingf(4)?

• Inefficiency:– Samethingiscomputed

severaltimes.

f(4)

f(3) f(2)

f(1)f(2) f(0)f(1)

f(1) f(0)

called9times

Autumn Semester2019

Page 44: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 44

PerformanceTip

• AvoidFibonacci-stylerecursiveprogramswhichresultinanexponential“explosion” ofcalls.

• Avoidusingrecursioninperformancesituations.

• Recursivecallstaketimeandconsumeadditionalmemory.

Autumn Semester2019

Page 45: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Fibonaccinumber:iterativeversion

Autumn Semester2019 Programming and DataStructure 45

#include <stdio.h>int f (int x);

int main(){

printf (“\n %d %d %d %d”, f(2), f(3), f(4), f(5));}

int f (int n){

int a = 0, b = 1, temp, i;for (i=2; i<=n; i++){

temp = a + b;a = b;b = temp;

}return (b);

}

Output:

1 2 3 5

Page 46: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 46

Example4::TowersofHanoiProblem

54321

LEFT CENTER RIGHT

Autumn Semester2019

Page 47: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 47

• Theproblemstatement:– InitiallyallthedisksarestackedontheLEFT pole.– RequiredtotransferallthediskstotheRIGHT pole.

• Onlyonediskcanbemovedatatime.• Alargerdiskcannotbeplacedonasmallerdisk.

– CENTER poleisusedfortemporarystorageofdisks.

Autumn Semester2019

Page 48: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 48

• Recursivestatementofthegeneralproblemofndisks.– Step1:

• Movethetop(n-1)disksfromLEFTtoCENTER.

– Step2:• MovethelargestdiskfromLEFTtoRIGHT.

– Step3:• Movethe(n-1)disksfromCENTERtoRIGHT.

Autumn Semester2019

Page 49: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 49

#include <stdio.h>

void transfer (int n, char from, char to, char temp);

main(){

int n; /* Number of disks */scanf (ʺ%dʺ, &n);transfer (n, ’L’, ’R’, ’C’);

}

void transfer (int n, char from, char to, char temp){

if (n > 0) {transfer (n-1, from, temp, to);printf (ʺMove disk %d from %c to %c \nʺ, n, from, to);transfer (n-1, temp, to, from);

}return;

}

Autumn Semester2019

Page 50: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 50Autumn Semester2019

3Move disk 1 from L to R Move disk 2 from L to C Move disk 1 from R to C Move disk 3 from L to R Move disk 1 from C to L Move disk 2 from C to R Move disk 1 from L to R

4Move disk 1 from L to C Move disk 2 from L to R Move disk 1 from C to R Move disk 3 from L to C Move disk 1 from R to L Move disk 2 from R to C Move disk 1 from L to C Move disk 4 from L to R Move disk 1 from C to R Move disk 2 from C to L Move disk 1 from R to L Move disk 3 from C to R Move disk 1 from L to C Move disk 2 from L to R Move disk 1 from C to R

Page 51: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 51Autumn Semester2019

Move disk 5 from L to RMove disk 1 from C to LMove disk 2 from C to RMove disk 1 from L to RMove disk 3 from C to LMove disk 1 from R to CMove disk 2 from R to LMove disk 1 from C to LMove disk 4 from C to RMove disk 1 from L to RMove disk 2 from L to CMove disk 1 from R to CMove disk 3 from L to RMove disk 1 from C to LMove disk 2 from C to RMove disk 1 from L to R

5Move disk 1 from L to RMove disk 2 from L to CMove disk 1 from R to CMove disk 3 from L to RMove disk 1 from C to LMove disk 2 from C to RMove disk 1 from L to RMove disk 4 from L to CMove disk 1 from R to CMove disk 2 from R to LMove disk 1 from C to LMove disk 3 from R to CMove disk 1 from L to RMove disk 2 from L to CMove disk 1 from R to C

Page 52: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 52

Recursionvs.Iteration

• Repetition– Iteration:explicitloop– Recursion:repeatedfunctioncalls

• Termination– Iteration:loopconditionfails– Recursion:basecaserecognized

• Bothcanhaveinfiniteloops• Balance

– Choicebetweenperformance(iteration)andgoodsoftwareengineering(recursion).

Autumn Semester2019

Page 53: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 53

Howarefunctioncallsimplemented?

• Thefollowingappliesingeneral,withminorvariationsthatareimplementationdependent.– Thesystemmaintainsastackinmemory.

• Stackisalast-infirst-outstructure.• Twooperationsonstack,push andpop.

– Wheneverthereisafunctioncall,theactivationrecordgetspushedintothestack.• Activationrecordconsistsof:

– thereturnaddressinthecallingprogram,– thereturnvaluefromthefunction,and– thelocalvariablesinsidethefunction.

Autumn Semester2019

Page 54: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 54

main(){

……..x = gcd (a, b);……..

}

int gcd (int x, int y){

……..……..return (result);

}

ReturnAddrReturnValue

LocalVariables

Beforecall Aftercall Afterreturn

STAC

K

Activationrecord

Autumn Semester2019

Page 55: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 55

main(){

……x=ncr(a,b);……

}

int ncr (int n,int r){return (fact(n)/fact(r)/fact(n-r));

}

LV1,RV1,RA1

Beforecall Callfact ncrreturns

int fact (int n){………return(result);

}

3 times

LV1,RV1,RA1

factreturns

LV1,RV1,RA1

LV2,RV2,RA2

Callncr

3times

Autumn Semester2019

Page 56: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 56

Whathappensforrecursivecalls?

• Whatwehaveseen….– Activationrecordgetspushedintothestackwhenafunctioncallismade.

– Activationrecordispoppedoffthestackwhenthefunctionreturns.

• Inrecursion,afunctioncallsitself.– Severalfunctioncallsgoingon,withnoneofthefunctioncallsreturningback.• Activationrecordsarepushedontothestackcontinuously.• Largestackspacerequired.• Activationrecordskeeppoppingoff,whentheterminationconditionofrecursionisreached.

Autumn Semester2019

Page 57: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 57

• Weshallillustratetheprocessbyanexampleofcomputingfactorial.– Activationrecordlookslike:

Return AddrReturn Value

Local Variables

Autumn Semester2019

Page 58: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 58

Example::main() callsfact(3)

int fact (n)int n;{

if (n == 0)return (1);

elsereturn (n * fact(n-1));

}

main(){

int n;n = 3;printf (”%d \n”, fact(n) );

}

Autumn Semester2019

Page 59: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 59

RA..main-

n=3

RA..main-

n=3RA..fact

-n=2

RA..main-

n=3RA..fact

-n=2

RA..fact-

n=1

RA..main-

n=3RA..fact

-n=2

RA..fact-

n=1RA..fact

1n=0

RA..main-

n=3RA..fact

-n=2

RA..fact1*1=1n=1

RA..main-

n=3RA..fact2*1=2n=2

RA..main3*2=6n=3

TRACEOFTHESTACKDURINGEXECUTION

maincallsfact

factreturnstomain

Autumn Semester2019

Page 60: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 60

DoYourself

• TracetheactivationrecordsforthefollowingversionofFibonaccisequence.#include <stdio.h>int f (int n){

int a, b;if (n < 2) return (n);else {a = f(n-1);b = f(n-2);return (a+b); }

}

main() {printf(ʺFib(4) is: %d \nʺ, f(4));

}

Return Addr(either main,

or X, or Y)

Return Value

Local Variables(n, a, b)

Autumn Semester2019

X

Y

main

Page 61: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

StorageClassofVariables

Page 62: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 62

WhatisStorageClass?

• Storageclassofavariabledecides

– thepermanence ofavariable:howlongavariableexistsinthememory

– itsscope withinaprogram:fromwhichpartsoftheprogramisavariableaccessible

• FourstorageclassspecificationsinC:– Automatic: auto– External: extern– Static: static– Register: register

Autumn Semester2019

Page 63: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 63

AutomaticVariables

• Thesearealwaysdeclaredwithinafunctionandarelocaltothefunctioninwhichtheyaredeclared.– Scopeisconfinedtothatfunction.

• Thisisthedefaultstorageclassspecification.– Allvariablesareconsideredasauto unlessexplicitlyspecifiedotherwise.

– Thekeywordauto isoptional.– Anautomaticvariabledoesnotretainitsvalueoncecontrolistransferredoutofitsdefiningfunction.

Autumn Semester2019

Page 64: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 64

#include <stdio.h>

int factorial(int m){

auto int i;auto int temp=1;for (i=1; i<=m; i++)

temp = temp * i;return (temp);

}

main(){

auto int n;for (n=1; n<=10; n++)printf (ʺ%d! = %d \nʺ,

n, factorial (n));}

Autumn Semester2019

Page 65: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 65

StaticVariables

• Staticvariablesaredefinedwithinindividual functionsandhavethesamescopeasautomaticvariables.

• Unlikeautomaticvariables,staticvariablesretaintheirvaluesthroughoutthelifeoftheprogram.– Ifafunctionisexitedandre-enteredatalatertime,thestatic

variablesdefinedwithinthatfunctionwillretaintheirpreviousvalues.

– Initialvaluescanbeincludedinthestaticvariabledeclaration.• Willbeinitializedonlyonce.

• Anexampleofusingstaticvariable:– Countnumberoftimesafunctioniscalled.

Autumn Semester2019

Page 66: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 66

#include <stdio.h>

int factorial (int n){static int count=0;count++;printf (ʺn=%d, count=%d \nʺ, n, count);if (n == 0) return 1;else return (n * factorial(n-1));

}

main(){

int i=6;printf (ʺValue is: %d \nʺ, factorial(i));

}

EXAMPLE 1

Autumn Semester2019

Page 67: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 67

• Programoutput:n=6, count=1n=5, count=2n=4, count=3n=3, count=4

n=2, count=5n=1, count=6n=0, count=7Value is: 720

Autumn Semester2019

Page 68: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 68

#include <stdio.h>

int fib (int n){static int count=0;count++;printf (ʺn=%d, count=%d \nʺ, n, count);if (n < 2) return n;else return (fib(n-1) + fib(n-2));

}

main(){

int i=4;printf (ʺValue is: %d \nʺ, fib(i));

}

EXAMPLE 2

Autumn Semester2019

Page 69: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 69

• Programoutput:n=4, count=1n=3, count=2n=2, count=3n=1, count=4

n=0, count=5n=1, count=6n=2, count=7n=1, count=8

n=0, count=9Value is: 3 [0,1,1,2,3,5,8,….]

f(4)

f(3) f(2)

f(1)f(2) f(0)f(1)

f(1) f(0)

Autumn Semester2019

Page 70: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 70

RegisterVariables

• Thesevariablesarestoredinhigh-speedregisterswithintheCPU.– Frequentlyusedvariablesmaybedeclaredasregistervariables.

– Resultsinincreaseinexecutionspeed.– Theallocation isdonebythecompiler.

Autumn Semester2019

Page 71: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 71

ExternalVariables

• Theyarenotconfinedtosinglefunctions.• Theirscopeextendsfromthepointofdefinitionthroughtheremainderoftheprogram.– Theymayspanmorethanonefunctions.– Alsocalledglobalvariables.

• Alternatewayofdeclaringglobalvariables.– Declarethemoutsidethefunction,atthebeginning.

• Advisednottouseexternalvariablesoften– riskofaccidentalchangeinsomefunction

Autumn Semester2019

Page 72: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 72

#include <stdio.h>

int count=0; /** GLOBAL VARIABLE **/int factorial (int n){count++;printf (ʺn=%d, count=%d \nʺ, n, count);if (n == 0) return 1;else return (n * factorial(n-1));

}

main() {int i=6;printf (ʺValue is: %d \nʺ, factorial(i));printf (ʺCount is: %d \nʺ, count);

}

Autumn Semester2019

Page 73: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Programming and DataStructure 73

Local&globalvariablesofsamename

• IfalocalvariabledeclaredwithinafunctionFhasthesamenameasaglobalvariable– ReferencestothisvariablefromwithinFwouldrefertothelocalvariable

Autumn Semester2019

int k = 8, m = 7;

void func(){int k = 6;printf (ʺk:%d \nʺ, k); // local variableprintf (ʺm:%d \nʺ, m); // global variable

}

Page 74: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

SOMEEXAMPLESONRECURSION

Autumn Semester2019 Programming and DataStructure 74

Page 75: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

GCDComputation…CorrectVersion#include <stdio.h>int gcd (m, n)int m, n;{

if (m == 0) return n;if (n == 0) return m;if (m == n) return (m);if (m > n)

return gcd (m%n, n);else

return gcd (m, n%m);}

int main(){int num1, num2;scanf ("%d %d", &num1, &num2);printf ("\nGCD of %d and %d is %d", num1, num2, gcd(num1,num2));

}

Autumn Semester2019 Programming and DataStructure 75

GCD of 12 and 12 is 12GCD of 15 and 0 is 15

GCD of 0 and 25 is 25

GCD of 156 and 66 is 6

GCD of 75 and 925 is 25

Page 76: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Computepowerab

// Compute a to the power b#include <stdio.h>

long int power (int a, int b){long int res = 1;if (b == 0) return (1);else return (a * power(a,b-1));

}

int main(){int x, y;long int result;scanf ("%d %d", &x, &y);result = power (x, y);printf ("\n%d to the power %d is %ld", x, y, result);

}

Autumn Semester2019 Programming and DataStructure 76

3 to the 4 is 812 to the power 16 is 65536

2 to the power 8 is 256

17 to the power 4 is 83521

436 to the power 0 is 1

Page 77: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

Sumofdigitsofanumber// Find sum of the digits of a number#include <stdio.h>

int digitsum (int num){int digit;if (num == 0) return (0);else {

digit = num % 10;return (digit + digitsum(num/10));

}}

int main(){int a;scanf ("%d", &a);printf ("\nSum of digits of %d is %d", a, digitsum(a));

}Autumn Semester2019 Programming and DataStructure 77

Sum of digits of 25 is 7Sum of digits of 23863 is 22

Sum of digits of 11111 is 5

Sum of digits of 0 is 0

Sum of digits of 9999 is 36

Page 78: Functionscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L3-Function.pdf · Calling Functions: Call by Value and Call by Reference • Used when invoking functions. • Call by

DecimaltoBinary// Print a decimal number in binary#include <stdio.h>

void dec2bin (int n){if (n == 0) return;else {

dec2bin (n/2);printf ("%2d", n%2);

}}

int main(){int dec;scanf ("%d", &dec);printf ("\nBinary of %d is",

dec);dec2bin (dec);

}Autumn Semester2019 Programming and DataStructure 78

Binary of 25 is 1 1 0 0 1Binary of 12 is 1 1 0 0

Binary of 128 is 1 0 0 0 0 0 0 0

Binary of 254 is 1 1 1 1 1 1 1 0