dale roberts csci 230 functions department of computer and information science, school of science,...

33
Dale Robert CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Dale Roberts, Lecturer IUPUI IUPUI [email protected] [email protected]

Upload: jessie-ball

Post on 18-Jan-2018

229 views

Category:

Documents


3 download

DESCRIPTION

Dale Roberts Program Modules in C Functions Modules in C Programs combine user-defined functions with library functions C standard library has a wide variety of functions Math function, I/O, string function, such as printf(), scanf() Function calls Invoking functions Provide function name and arguments (data) Function performs operations or manipulations Function returns results Write function once and call it many times Function call analogy: Boss asks worker to complete task Worker gets information, does task, returns result Information hiding: boss does not know details

TRANSCRIPT

Page 1: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

CSCI 230

Functions

Department of Computer and Information Science,School of Science, IUPUI

Dale Roberts, LecturerDale Roberts, [email protected]@cs.iupui.edu

Page 2: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

IntroductionIntroductionFunctionsFunctionsCategory Programmers Duration Size of Code

TrivialTrivial 1 1 1-2 weeks1-2 weeks < 500 lines (student homework)< 500 lines (student homework)SmallSmall 1 - 3 1 - 3 Few WeeksFew Weeks 500 -2000 lines (term projects)500 -2000 lines (term projects)MediumMedium 2 - 5 2 - 5 Few MonthsFew Months 2000 -10000 (research project)2000 -10000 (research project)LargeLarge 5-25 5-25 1 - 3 years1 - 3 years 10,000 - 100,000 (current 10,000 - 100,000 (current

application)application)Very LargeVery Large 25-100 25-100 3 - 5 years3 - 5 years 100,000 - 1M (real-time 100,000 - 1M (real-time

operations)operations)Extremely Large > 100Extremely Large > 100 > 5 years> 5 years >1M (advanced military work)>1M (advanced military work)

Divide and conquer Divide and conquer Large programs cannot be monolithicLarge programs cannot be monolithicConstruct a program from smaller pieces or components. These Construct a program from smaller pieces or components. These smaller pieces are called modulessmaller pieces are called modulesEach piece is more manageable than the original programEach piece is more manageable than the original program

Page 3: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Program Modules in CProgram Modules in CFunctionsFunctions

Modules in CModules in CPrograms combine user-defined functions with library functionsPrograms combine user-defined functions with library functions

C standard library has a wide variety of functionsC standard library has a wide variety of functionsMath function, I/O, string function, such as Math function, I/O, string function, such as printf()printf(), , scanf()scanf()

Function callsFunction callsInvoking functionsInvoking functions

Provide function name and arguments (data)Provide function name and arguments (data)Function performs operations or manipulationsFunction performs operations or manipulationsFunction returns resultsFunction returns resultsWrite function once and call it many timesWrite function once and call it many times

Function call analogy:Function call analogy:Boss asks worker to complete taskBoss asks worker to complete task

Worker gets information, does task, returns resultWorker gets information, does task, returns resultInformation hiding: boss does not know detailsInformation hiding: boss does not know details

Page 4: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Math Library FunctionsMath Library FunctionsMath library functions Math library functions

perform common mathematical calculationsperform common mathematical calculations #include <math.h>#include <math.h>

Format for calling functionsFormat for calling functions FunctionName(FunctionName( argumentargument ););

If multiple arguments, use comma-separated listIf multiple arguments, use comma-separated list

printf( "%.2f", sqrt( 900.0 ) ); printf( "%.2f", sqrt( 900.0 ) ); Calls function Calls function sqrtsqrt, which returns the square root of its argument, which returns the square root of its argumentAll math functions return data type All math functions return data type doubledouble

Arguments may be constants, variables, or expressionsArguments may be constants, variables, or expressions

Page 5: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

FunctionsFunctionsFunctionsFunctions

Modularize a programModularize a programAll variables declared inside functions are local variablesAll variables declared inside functions are local variables

Known only in function definedKnown only in function defined

ParametersParametersCommunicate information between functionsCommunicate information between functionsLocal variablesLocal variables

Benefits of functionsBenefits of functionsDivide and conquerDivide and conquer

Manageable program developmentManageable program development

Software reusabilitySoftware reusabilityUse existing functions as building blocks for new programsUse existing functions as building blocks for new programsAbstraction - hide internal details (library functions)Abstraction - hide internal details (library functions)

Avoid code repetitionAvoid code repetition

Page 6: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Function DefinitionsFunction DefinitionsFunction definition formatFunction definition formatreturn-value-type function-name( parameter-list )return-value-type function-name( parameter-list ){{ declarations and statements declarations and statements} }

Function-name: any valid identifierFunction-name: any valid identifierReturn-value-type: data type of the result (default Return-value-type: data type of the result (default intint))

voidvoid –– indicates that the function returns nothing indicates that the function returns nothingAn unspecified return-value-type is always assumed by the compiler to be An unspecified return-value-type is always assumed by the compiler to be intint

Parameter-list: comma separated list, declares parametersParameter-list: comma separated list, declares parametersA type must be listed explicitly for each parameter, unless the parameter is of type A type must be listed explicitly for each parameter, unless the parameter is of type intint

Declarations and statements: function body (block)Declarations and statements: function body (block)Variables can be declared inside blocks (can be nested)Variables can be declared inside blocks (can be nested)Functions can not be defined inside other functionsFunctions can not be defined inside other functions

Returning controlReturning controlIf nothing returned If nothing returned

return;return; or, until reaches right braceor, until reaches right brace

If something returned If something returned returnreturn expressionexpression;;

Page 7: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

1 /* Fig. 5.4: fig05_04.c2 Finding the maximum of three integers */3 #include <stdio.h>45 int maximum( int, int, int ); /* function prototype */67 int main()8 {9 int a, b, c;1011 printf( "Enter three integers: " );12 scanf( "%d%d%d", &a, &b, &c );13 printf( "Maximum is: %d\n", maximum( a, b, c ) );1415 return 0;16 }1718 /* Function maximum definition */19 int maximum( int x, int y, int z )20 {21 int max = x;2223 if ( y > max )24 max = y;2526 if ( z > max )27 max = z;2829 return max;30 }

Enter three integers: 22 85 17Maximum is: 85

1. Function prototype(3 parameters)

2. Input values

3. Call function

4. Function definition

Program Output

Page 8: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Function PrototypesFunction PrototypesFunction prototype Function prototype

Function nameFunction nameParameters Parameters –– what the function takes in what the function takes inReturn type Return type –– data type function returns (default data type function returns (default intint))Used to validate functionsUsed to validate functionsPrototype only needed if function definition comes Prototype only needed if function definition comes afterafter use in programuse in programThe function with the prototypeThe function with the prototype

int maximum( int, int, int );int maximum( int, int, int );Takes in 3 Takes in 3 intintssReturns an Returns an intint

Promotion rules and conversionsPromotion rules and conversionsConverting to lower types can lead to errorsConverting to lower types can lead to errors

Page 9: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

ExamplesExamplesfloat plus1(float x,y) {

float sum;float sum;sum = x + y;sum = x + y;return sum;return sum;

}}

plus2(int x,y) {

int sum;sum = x + y;return sum;

}

• The minimal function is dummy(){}• Again, the return statement can be

return expression; Example: return a*a;return (expression); Example: return ((a > 0)? a, -a));return;

• In conclusion, to call a function from another function, you should:1. Declare the type of the called function, if not a int function2. Use format of function_name(actual parameters)

Page 10: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

float mySquare(x)float x;{

return x*x;}

More Examples:More Examples:Example 1: …

float mySquare(float);main()

{ float y; printf(%f\n, mySquare(5.0)); }

float mySquare(float x) {

return x*x;}

Old style

Example 2: /* calculate the sum from 1+2+…+n */ int sum(int n) {

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

sum += i;return(sum);

}

main() {

int j,n;printf(“input value n: “);scanf(“%d”,&n);for (j=1; j<=n; j++) printf(“sum from 1 to %d is %d\n”,j,sum(j));

}

How can we have both a function and a variable named “sum?”

Page 11: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Header FilesHeader FilesHeader filesHeader files

Contain function prototypes for library functionsContain function prototypes for library functions<stdlib.h><stdlib.h> , , <math.h><math.h> , etc , etcLoad with Load with #include <filename>#include <filename>#include <math.h>#include <math.h>

Custom header filesCustom header filesCreate file with functions Create file with functions Save as Save as filename.hfilename.hLoad in other files with Load in other files with #include "filename.h"#include "filename.h"Reuse functionsReuse functions

Page 12: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Calling Functions:Calling Functions:Call by Value and Call by ReferenceCall by Value and Call by Reference

Used when invoking functionsUsed when invoking functionsCall by valueCall by value

Copy of argument passed to functionCopy of argument passed to functionChanges in function do not effect originalChanges in function do not effect originalUse when function does not need to modify argumentUse when function does not need to modify argument

Avoids accidental changesAvoids accidental changesExampleExample::addone(int);addone(int);main ()main ()

{{int i = 5, j;int i = 5, j;j=addone(i);j=addone(i);printf(“%d %d\n”,i, j);printf(“%d %d\n”,i, j); 5 65 6

}}

addone(int x)addone(int x){{return ++x;return ++x;

}}

Page 13: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Calling Functions:Calling Functions:Call by Value and Call by ReferenceCall by Value and Call by Reference

Call by reference (Passing Address)Call by reference (Passing Address)This is not actually call by reference, although some books called This is not actually call by reference, although some books called this ‘call-by-reference’this ‘call-by-reference’Passes original argumentPasses original argumentChanges in function effect original using Changes in function effect original using && operator to pass address operator to pass addressOnly used with trusted functionsOnly used with trusted functions

ExampleExample::addone(int);addone(int);main ()main (){{int i = 5, j;int i = 5, j;j=addone(&i);j=addone(&i);printf(“%d %d\n”,i, j);printf(“%d %d\n”,i, j); 6 66 6}}

addone(int *x)addone(int *x){{return ++(*x);return ++(*x);

}}For now, we focus on call by valueFor now, we focus on call by value

Page 14: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Random Number GenerationRandom Number Generationrandrand function function

Load Load <stdlib.h><stdlib.h>Returns "random" number between Returns "random" number between 00 and and RAND_MAXRAND_MAX (at least (at least 3276732767))

i = rand();i = rand();

PseudorandomPseudorandomPreset sequence of "random" numbersPreset sequence of "random" numbersSame sequence for every function callSame sequence for every function call

ScalingScalingTo get a random number between To get a random number between 11 and and nn

1 + ( rand() % n )1 + ( rand() % n )rand() % nrand() % n returns a number between returns a number between 00 and and n-1n-1Add Add 11 to make random number between to make random number between 11 and and nn1 + ( rand() % 6)1 + ( rand() % 6)

number between number between 11 and and 66

Page 15: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Random Number GenerationRandom Number Generation

srandsrand function function<stdlib.h><stdlib.h>Takes an integer seed and jumps to that location in its Takes an integer seed and jumps to that location in its "random" sequence"random" sequence

srand(srand( seed seed ););

srand( time( NULL ) ); //load <time.h>srand( time( NULL ) ); //load <time.h>time( NULL )time( NULL )

Returns the time at which the program was compiled in seconds Returns the time at which the program was compiled in seconds ““Randomizes" the seedRandomizes" the seed

Page 16: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

 Enter seed: 67 6 1 4 6 2 1 6 1 6 4

1 /* Fig. 5.9: fig05_09.c2 Randomizing die-rolling program */3 #include <stdlib.h>4 #include <stdio.h>56 int main()7 {8 int i;9 unsigned seed;10 11 printf( "Enter seed: " );12 scanf( "%u", &seed );13 srand( seed );14 15 for ( i = 1; i <= 10; i++ ) {16 printf( "%10d", 1 + ( rand() % 6 ) );17 18 if ( i % 5 == 0 )19 printf( "\n" );20 }2122 return 0;23 }

Enter seed: 867 2 4 6 1 6 1 1 3 6 2

Enter seed: 67 6 1 4 6 2 1 6 1 6 4

1. Initialize seed

2. Input value for seed3. Use srand to change random sequence

4. Define Loop 5. Generate and output random numbers Program Output

Page 17: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Example: A Game of ChanceExample: A Game of ChanceCraps simulatorCraps simulatorRulesRules

Roll two diceRoll two dice7 or 11 on first throw, player wins7 or 11 on first throw, player wins2, 3, or 12 on first throw, player loses2, 3, or 12 on first throw, player loses4, 5, 6, 8, 9, 10 - value becomes player's "point"4, 5, 6, 8, 9, 10 - value becomes player's "point"

Player must roll his point before rolling 7 to winPlayer must roll his point before rolling 7 to win

Example:Example:1111121210, 6, 11, 6, 1010, 6, 11, 6, 104, 5, 9, 10, 9, 3, 74, 5, 9, 10, 9, 3, 7

Page 18: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

1 /* Fig. 5.10: fig05_10.c2 Craps */3 #include <stdio.h>4 #include <stdlib.h>5 #include <time.h>67 int rollDice( void );89 int main()10 {11 int gameStatus, sum, myPoint;1213 srand( time( NULL ) );14 sum = rollDice(); /* first roll of the dice */1516 switch ( sum ) {17 case 7: case 11: /* win on first roll */18 gameStatus = 1;19 break;20 case 2: case 3: case 12: /* lose on first roll */21 gameStatus = 2;22 break;23 default: /* remember point */24 gameStatus = 0;25 myPoint = sum;26 printf( "Point is %d\n", myPoint );27 break;28 }2930 while ( gameStatus == 0 ) { /* keep rolling */31 sum = rollDice();32

1. rollDice prototype

2. Initialize variables3. Seed srand

4. Define switch statement for win/loss/continue

5. Loop

Page 19: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Player rolled 6 + 5 = 11Player wins

33 if ( sum == myPoint ) /* win by making point */34 gameStatus = 1;35 else36 if ( sum == 7 ) /* lose by rolling 7 */37 gameStatus = 2;38 }3940 if ( gameStatus == 1 )41 printf( "Player wins\n" );42 else43 printf( "Player loses\n" );4445 return 0;46 }4748 int rollDice( void )49 {50 int die1, die2, workSum;5152 die1 = 1 + ( rand() % 6 );53 die2 = 1 + ( rand() % 6 );54 workSum = die1 + die2;55 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum );

56 return workSum;57 }

6. Print win/lossPlayer rolled 6 + 6 = 12Player loses

Player rolled 4 + 6 = 10Point is 10Player rolled 2 + 4 = 6Player rolled 6 + 5 = 11Player rolled 3 + 3 = 6Player rolled 6 + 4 = 10Player wins Player rolled 1 + 3 = 4Point is 4Player rolled 1 + 4 = 5Player rolled 5 + 4 = 9Player rolled 4 + 6 = 10Player rolled 6 + 3 = 9Player rolled 1 + 2 = 3Player rolled 5 + 2 = 7Player loses

Program Output

Page 20: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Storage ClassesStorage ClassesStorage class specifiersStorage class specifiers

Storage duration Storage duration –– how long an object exists in memory how long an object exists in memoryScope Scope –– where object can be referenced in program where object can be referenced in programLinkage Linkage –– specifies the files in which an identifier is known (more in specifies the files in which an identifier is known (more in Chapter 14)Chapter 14)

Automatic storageAutomatic storageObject created and destroyed within its blockObject created and destroyed within its blockautoauto: default for local variables and usually stored in : default for local variables and usually stored in StackStack..

auto double x, y;auto double x, y;registerregister: tries to put variable into high-speed registers: tries to put variable into high-speed registers

Can only be used for automatic variablesCan only be used for automatic variablesregister int counter = 1;register int counter = 1;ExampleExample:: f(register int c, register int n)f(register int c, register int n)

{{register int i;register int i;……

}}

Page 21: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Storage ClassesStorage ClassesStatic storage Static storage

Variables exist for entire program executionVariables exist for entire program executionDefault value of zeroDefault value of zerostaticstatic: local variables defined in functions. : local variables defined in functions.

Keep value after function endsKeep value after function endsOnly known in their own function; Only known in their own function;

ExampleExample:: static char buf[128];static char buf[128];static int bufp=0;static int bufp=0;getch1()getch1(){{

……}}

Page 22: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

1 /* Fig. 5.12: fig05_12.c2 A scoping example */3 #include <stdio.h>45 void a( void ); /* function prototype */6 void b( void ); /* function prototype */7 void c( void ); /* function prototype */89 int x = 1; /* global variable */1011 int main()12 {13 int x = 5; /* local variable to main */1415 printf("local x in outer scope of main is %d\n", x );1617 { /* start new scope */18 int x = 7;1920 printf( "local x in inner scope of main is %d\n", x );21 } /* end new scope */2223 printf( "local x in outer scope of main is %d\n", x );2425 a(); /* a has automatic local x */26 b(); /* b has static local x */27 c(); /* c uses global x */28 a(); /* a reinitializes automatic local x */29 b(); /* static local x retains its previous value */30 c(); /* global x also retains its value */

1. Function prototypes

2. Initialize global variable

3. Initialize local variable

4. Initialize local variable in block

5. Call functions

6. Output results

Page 23: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

3132 printf( "local x in main is %d\n", x );33 return 0;34 }3536 void a( void )37 {38 int x = 25; /* initialized each time a is called */3940 printf( "\nlocal x in a is %d after entering a\n", x );41 ++x;42 printf( "local x in a is %d before exiting a\n", x );43 }4445 void b( void )46 {47 static int x = 50; /* static initialization only */48 /* first time b is called */49 printf( "\nlocal static x is %d on entering b\n", x );50 ++x;51 printf( "local static x is %d on exiting b\n", x );52 }5354 void c( void )55 {56 printf( "\nglobal x is %d on entering c\n", x );57 x *= 10;58 printf( "global x is %d on exiting c\n", x );59 }

local x in outer scope of main is 5local x in inner scope of main is 7local x in outer scope of main is 5 local x in a is 25 after entering alocal x in a is 26 before exiting a local static x is 50 on entering blocal static x is 51 on exiting b global x is 1 on entering cglobal x is 10 on exiting c local x in a is 25 after entering alocal x in a is 26 before exiting a local static x is 51 on entering blocal static x is 52 on exiting b global x is 10 on entering cglobal x is 100 on exiting clocal x in main is 5

7. Function definitions Program Output

Page 24: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Scope RulesScope RulesFile scope File scope

Identifier defined outside function, known in all functionsIdentifier defined outside function, known in all functionsUsed for global variables, function definitions, function prototypesUsed for global variables, function definitions, function prototypes

Function scope Function scope Can only be referenced inside a function bodyCan only be referenced inside a function bodyUsed only for labels (Used only for labels (start:start:, , case:case: , etc.) , etc.)

Block scope Block scope Identifier declared inside a block Identifier declared inside a block

Block scope begins at declaration, ends at right braceBlock scope begins at declaration, ends at right brace

Used for variables, function parameters (local variables of function)Used for variables, function parameters (local variables of function)Outer blocks "hidden" from inner blocks if there is a variable with Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner blockthe same name in the inner block

Function prototype scope Function prototype scope Used for identifiers in parameter listUsed for identifiers in parameter list

Page 25: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

externextern Storage Class Specifier Storage Class SpecifierIf an external variable is to be referred to before it is defined, or if it is defined If an external variable is to be referred to before it is defined, or if it is defined in a different source file from the one where it is being used, thenin a different source file from the one where it is being used, then extern extern declaration is necessarydeclaration is necessaryexternextern: default for global variables and functions: default for global variables and functions

Known in any functionKnown in any functionUsage: if large number of variables must be shared among functions, external Usage: if large number of variables must be shared among functions, external variables are more convenient and efficient than long argument listvariables are more convenient and efficient than long argument list

ExampleExample::In file 1:In file 1: ……

int sp=0;int sp=0;double val[12];double val[12];……

In file 2;In file 2;extern int sp;extern int sp;extern double val[];extern double val[];int push(f)int push(f)double f;double f;{{

……}}……

Page 26: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

RecursionRecursionRecursive functions

A function can invoke any other function; A function can invoke any other function; “ Can a function invoke itself?”“ Can a function invoke itself?”Functions that call themselves either directly or indirectly (through another Functions that call themselves either directly or indirectly (through another function) is called a function) is called a recursive functionrecursive function..A recursive function is called to solve a problem. The function actually knows A recursive function is called to solve a problem. The function actually knows how to solve the simplest case(s) - “how to solve the simplest case(s) - “base casebase case” and simply returns a result.” and simply returns a result.If a function is called with a complex case, it divides the problem into two If a function is called with a complex case, it divides the problem into two conceptual places:conceptual places:

What it can doWhat it can doWhat it cannot do:What it cannot do:

1.1. must resembles original problem but slightly simplifiedmust resembles original problem but slightly simplified2.2. function will call itself (recursion step or recursive call) to solve slightly simplified function will call itself (recursion step or recursive call) to solve slightly simplified

problemproblem3.3. process continues until the last recursive call is with the base caseprocess continues until the last recursive call is with the base case4.4. that call returns the result of the base casethat call returns the result of the base case5.5. return to previous calling functionreturn to previous calling function6.6. finally reaches main.c and goes back to 2.finally reaches main.c and goes back to 2.

Eventually base case gets solvedEventually base case gets solvedGets plugged in, works its way up and solves whole problemGets plugged in, works its way up and solves whole problem

Page 27: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Recursion Recursion (cont.)(cont.)

ExampleExample: Compute : Compute x x yy for for x x > 0> 0 & & y y > 0> 0x y = x * x * x * … * x

base case: x1 = x x y = x1 * ( x * x * … * x)

= x1 * ( x1 * ( x * x * … * x ))= x1 * ( x1 * ( x1 * ( x * x * … * x )))

ex. x 4 = x1 * ( x1 * ( x1 * ( x1 )))

Fundamental rules of recursionFundamental rules of recursion1.) Base cases1.) Base cases2.) Making progress through recursion2.) Making progress through recursion3.) Design rule: assuming all recursive call work (details hidden)3.) Design rule: assuming all recursive call work (details hidden)4.) Compound interest rule: do not duplicate recursive calls4.) Compound interest rule: do not duplicate recursive calls

Always specify the base case; otherwise, indefinite recursive will Always specify the base case; otherwise, indefinite recursive will occur and cause “occur and cause “stack-overflowstack-overflow” error.” error.

x1

x1

x1

x1

*

*

*x1

x3

x2

x1

x2

x3

x4x4

5

51

51

51

*

*

*51

53

52

x1

x2

125

62554

25

5

y times

Page 28: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Recursion: #include <stdio.h>

int x_pow_y(int, int);

main(){ printf(“enter x and y: \n”); scanf(“%d, %d”, x, y); z = x_pow_y(x,y); printf(“z: %d\n”, z);}

x_pow_y(int a, int b){ if (b==1)

return a; else

return (a * x_pow_y(a, b-1)) }

Recursion vs. IterationRecursion vs. IterationIteration: x_pow_y = 1;

for (i = y; i >=1; i--) x_pow_y*=x;

If x = 5, y = 4

x_pow_y = 1, x = 5, y = 4, i = 4;1.) x_pow_y = 5*1 = 5, i = 3;2.) x_pow_y = 5*5 = 25, i = 2;3.) x_pow_y = 25*5 = 125, i = 1;4.) x_pow_y = 125*5 = 625, i = 0;

…x=5;y=4;

x_pow_y(5,4);

…is (4==1)?

no

…is (3==1)?

no

…is (2==1)?

no

…is (1==1)?

yes

return 5

x_pow_y(5,4) x_pow_y(5,3) x_pow_y(5,2) x_pow_y(5,1)

Base Casemain5

25125625

Page 29: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Example Using Recursion: FactorialExample Using Recursion: FactorialExample: factorials: 5! = 5 * 4 * 3 * 2 * 1

Notice thatNotice that5! = 5 * 4!5! = 5 * 4!4! = 4 * 3! 4! = 4 * 3! ……

Can compute factorials recursively Can compute factorials recursively Solve base case (Solve base case (1! = 0! = 11! = 0! = 1) then plug in) then plug in

2! = 2 * 1! = 2 * 1 = 2;2! = 2 * 1! = 2 * 1 = 2;3! = 3 * 2! = 3 * 2 = 6;3! = 3 * 2! = 3 * 2 = 6;

long factorial(int n)long factorial(int n){{

if (n <= 1)if (n <= 1)return 1;return 1;elseelsereturn n * factorial(n-1);return n * factorial(n-1);

}}

 

00

)!1(

1!

nn

nnn

Page 30: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Example Using Recursion: The Fibonacci SeriesExample Using Recursion: The Fibonacci SeriesExample: Fibonacci series:

FFk k = = FFk-1 k-1 + + FFk-2k-2,, FF0 0 = 1, = 1, FF11 = 1 ex: = 1 ex: 1, 1, 2, 3, 5, 8…1, 1, 2, 3, 5, 8…

Each number is the sum of the previous two Each number is the sum of the previous two Can be solved recursively:Can be solved recursively:fib( n ) = fib( n - 1 ) + fib( n – 2 )fib( n ) = fib( n - 1 ) + fib( n – 2 )

Set of recursive calls to function Set of recursive calls to function fibonaccifibonacciCode for the Code for the fibaonaccifibaonacci function function

long fibonacci(long n)long fibonacci(long n){{ if (n <= 1)if (n <= 1) return 1;return 1;else;else;return return fibonaccifibonacci(n-1)+ (n-1)+ fibonaccifibonacci(n-2);(n-2);

}}

f( 3 )

f( 1 )f( 2 )

f( 1 ) f( 0 ) return 1

return 1 return 1

return +

+return

 

Page 31: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

1 /* Fig. 5.15: fig05_15.c2 Recursive fibonacci function */3 #include <stdio.h>45 long fibonacci( long );67 int main()8 {9 long result, number;1011 printf( "Enter an integer: " );12 scanf( "%ld", &number );13 result = fibonacci( number );14 printf( "Fibonacci( %ld ) = %ld\n", number, result );15 return 0;16 }1718 /* Recursive definition of function fibonacci */19 long fibonacci( long n )20 {21 if ( n == 0 || n == 1 )22 return n;23 else24 return fibonacci( n - 1 ) + fibonacci( n - 2 );25 }

Enter an integer: 0Fibonacci(0) = 0 Enter an integer: 1Fibonacci(1) = 1

Enter an integer: 2Fibonacci(2) = 1 Enter an integer: 3Fibonacci(3) = 2 Enter an integer: 4Fibonacci(4) = 3 Enter an integer: 5Fibonacci(5) = 5 Enter an integer: 6Fibonacci(6) = 8 Enter an integer: 10Fibonacci(10) = 55 Enter an integer: 20Fibonacci(20) = 6765 Enter an integer: 30Fibonacci(30) = 832040 Enter an integer: 35Fibonacci(35) = 9227465

1. Function prototype

2 Initialize variables

3. Input an integer4. Call function fibonacci

5. Output results.

6. Define fibonacci recursively

Page 32: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Recursion vs. IterationRecursion vs. IterationBoth are based on the control structuresBoth are based on the control structures

Repetition (Iteration): explicitly uses repetition (loop).Repetition (Iteration): explicitly uses repetition (loop).Selection (Recursion): implicitly use repetition by Selection (Recursion): implicitly use repetition by successive function callssuccessive function calls

Both involve terminationBoth involve terminationIteration: loop condition failsIteration: loop condition failsRecursion: base case recognizedRecursion: base case recognized

Both can lead indefinite loopsBoth can lead indefinite loopsLoop termination is not metLoop termination is not metBase case is not reachedBase case is not reached

Balance Balance Choice between performance (iteration) and good software Choice between performance (iteration) and good software engineering (recursion)engineering (recursion)

Page 33: Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer

Dale Roberts

Recursion vs. IterationRecursion vs. IterationAny problem that can be solved recursively can also be Any problem that can be solved recursively can also be solved iteratively. A recursion is chosen in preference solved iteratively. A recursion is chosen in preference over iteration while the recursive approach more naturally over iteration while the recursive approach more naturally mirrors the problem and results in a program that easier to mirrors the problem and results in a program that easier to understand and debug.understand and debug.Recursion has an overhead of repeated function calls Recursion has an overhead of repeated function calls which is expensive in terms of processor time ad memory which is expensive in terms of processor time ad memory usageusageAnother reason to choose recursion is that an iterative Another reason to choose recursion is that an iterative solution may not apparent.solution may not apparent.If used properly a recursive approach can lead to smaller If used properly a recursive approach can lead to smaller code size and elegant program (at the case of code size and elegant program (at the case of performance penalty.)performance penalty.)