L4 functions

47
Autumn Semester 2009 Programming and Data Structure 1 Functions Courtsey: University of Pittsburgh-CSD-Khalifa

Transcript of L4 functions

Page 1: L4 functions

Autumn Semester 2009 Programming and Data Structure 1

Functions

Courtsey: University of Pittsburgh-CSD-Khalifa

Page 2: L4 functions

Autumn Semester 2009 Programming and Data Structure 2

Class Test I: Time and Venue

• Date: August 20, 2009• Time: 6:00 PM to 7:00 PM

– Students must occupy seat within 5:45 PM, and carry library card with them.

• Venue: VIKRAMSHILA COMPLEX / MAIN BUILDING

- Section 7 & 10 (AE-EC) :: AE, AG, AR, BT, CE, CH, CS , CY, EC Room V1– Section 8 & 10 (Rest) :: Room V2– Section 9 (AE-CS):: AE, AG, AR, BT, CE, CH, CS Room V3– Section 9 (Rest):: Room V4– Section 11:: F 116– Section 12:: F 142

Page 3: L4 functions

Autumn Semester 2009 Programming and Data Structure 3

Functions: Why?

• Functions– Modularize a program– All variables declared inside functions are local

variables• Known only in function defined

– Parameters• Communicate information between functions• Local variables

• Benefits– Divide and conquer

• Manageable program development– Software reusability

• Use existing functions as building blocks for new programs

• Abstraction - hide internal details (library functions)– Avoids code repetition

Page 4: L4 functions

Autumn Semester 2009 Programming and Data Structure 4

Functions: Why?

• Divide and conquer – Construct a program from smaller

pieces or components– Each piece more manageable than the

original program

Page 5: L4 functions

Autumn Semester 2009 Programming and Data Structure 5

Program Modules in C

• Functions– Modules in C

– Programs written by combining user-defined functions with library functions

• C standard library has a wide variety of functions

• Makes programmer's job easier - avoid reinventing the wheel

Page 6: L4 functions

Autumn Semester 2009 Programming and Data Structure 6

Program Modules in C

• Function calls– Invoking functions

• Provide function name and arguments (data)• Function performs operations or

manipulations• Function returns results

– Boss asks worker to complete task• Worker gets information, does task, returns

result• Information hiding: boss does not know

details

Page 7: L4 functions

Autumn Semester 2009 Programming and Data Structure 7

Function: An Example#include <stdio.h>

int square(int x){ int y; y=x*x; return(y);}

void main() { int a,b,sum_sq;

printf(“Give a and b \n”); scanf(“%d%d”,&a,&b);

sum_sq=square(a)+square(b);

printf(“Sum of squares= %d \n”,sum_sq); }

Function definition

Name of function

parameter

Return data-type

Functions called

Parameters Passed

Page 8: L4 functions

Autumn Semester 2009 Programming and Data Structure 8

Invoking a function call : An Example• #include <stdio.h>

• int square(int x)• {• int y;• • y=x*x;• return(y);• }

• void main()• {• int a,b,sum_sq;

• printf(“Give a and b \n”);• scanf(“%d%d”,&a,&b);

• sum_sq=square(a)+square(b);

• printf(“Sum of squares= %d \n”,sum_sq);• }

Assume value of a is 10

10a

x 10

*

y 100

returns

Page 9: L4 functions

Autumn Semester 2009 Programming and Data Structure 9

Function Definitions

• Function definition format (continued)return-value-type function-name( parameter-list )

{ declarations and statements}

– Declarations and statements: function body (block)• Variables can be declared inside blocks (can be

nested)• Function can not be defined inside another function

– Returning control• If nothing returned

– return; – or, until reaches right brace

• If something returned – return expression;

Page 10: L4 functions

Autumn Semester 2009 Programming and Data Structure 10

Variable Scope

• int A;• void main()

• { A = 1;• myProc();• printf ( "A =

%d\n", A);• }

• void myProc()• { int A = 2;• while( A==2 )• {• int A = 3;• printf ( "A =

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

%d\n", A);• }• . . .

Printout:

--------------

A = 3

A = 2

A = 1

Page 11: L4 functions

Autumn Semester 2009 Programming and Data Structure 11

Math Library Functions

• Math library functions – perform common mathematical calculations– #include <math.h>

• Format for calling functionsFunctionName (argument);

• If multiple arguments, use comma-separated list

– printf( "%5.2f", sqrt( 900.0 ) ); • Calls function sqrt, which returns the square root of its

argument

• All math functions return data type double

– Arguments may be constants, variables, or expressions

Page 12: L4 functions

Autumn Semester 2009 Programming and Data Structure 12

Math Library Functions• double acos(double x) -- Compute arc cosine of x.

double asin(double x) -- Compute arc sine of x. double atan(double x) -- Compute arc tangent of x. double atan2(double y, double x) -- Compute arc tangent of y/x. double ceil(double x) -- Get smallest integral value that exceeds x. double cos(double x) -- Compute cosine of angle in radians. double cosh(double x) -- Compute the hyperbolic cosine of x. div_t div(int number, int denom) -- Divide one integer by another. double exp(double x -- Compute exponential of x double fabs (double x ) -- Compute absolute value of x. double floor(double x) -- Get largest integral value less than x. double fmod(double x, double y) -- Divide x by y with integral quotient and return remainder. double frexp(double x, int *expptr) -- Breaks down x into mantissa and exponent of no. labs(long n) -- Find absolute value of long integer n. double ldexp(double x, int exp) -- Reconstructs x out of mantissa and exponent of two. ldiv_t ldiv(long number, long denom) -- Divide one long integer by another. double log(double x) -- Compute log(x). double log10 (double x ) -- Compute log to the base 10 of x. double modf(double x, double *intptr) -- Breaks x into fractional and integer parts. double pow (double x, double y) -- Compute x raised to the power y. double sin(double x) -- Compute sine of angle in radians. double sinh(double x) - Compute the hyperbolic sine of x. double sqrt(double x) -- Compute the square root of x. void srand(unsigned seed) -- Set a new seed for the random number generator (rand). double tan(double x) -- Compute tangent of angle in radians. double tanh(double x) -- Compute the hyperbolic tangent of x.

http://www.cs.cf.ac.uk/Dave/C/node17.html#SECTION001710000000000000000

Page 13: L4 functions

Autumn Semester 2009 Programming and Data Structure 13

Function Prototypes

• Function prototype

– Function name– Parameters - what the function takes in– Return type - data type function returns (default int)– Used to validate functions– Prototype only needed if function definition comes after

use in programint maximum( int, int, int );

• Takes in 3 ints

• Returns an int

• Promotion rules and conversions– Converting to lower types can lead to errors

Page 14: L4 functions

Autumn Semester 2009 Programming and Data Structure 14

Header Files

• Header files– contain function prototypes for library functions– <stdlib.h> , <math.h> , etc– Load with #include <filename>

#include <math.h>

• Custom header files– Create file with functions – Save as filename.h– Load in other files with #include "filename.h"– Reuse functions

Page 15: L4 functions

Autumn Semester 2009 Programming and Data Structure 15

/* Finding the maximum of three integers */

#include <stdio.h>

int maximum( int, int, int ); /* function prototype */

int main(){ int a, b, c;

printf( "Enter three integers: " ); scanf( "%d%d%d", &a, &b, &c ); printf( "Maximum is: %d\n", maximum( a, b, c ) );

return 0;}

/* Function maximum definition */int maximum( int x, int y, int z ){ int max = x;

if ( y > max ) max = y;

if ( z > max ) max = z;

return max;}

Page 16: L4 functions

Autumn Semester 2009 Programming and Data Structure 16

Calling Functions: Call by Value and Call by Reference

• Used when invoking functions• Call by value

– Copy of argument passed to function– Changes in function do not affect original– Use when function does not need to modify argument

• Avoids accidental changes

• Call by reference – Passes original argument– Changes in function affect original– Only used with trusted functions

• For now, we focus on call by value

Page 17: L4 functions

Autumn Semester 2009 Programming and Data Structure 17

An Example: Random Number Generation

• rand function– Prototype defined in <stdlib.h>– Returns "random" number between 0 and RAND_MAX (at

least 32767)i = rand();

– Pseudorandom• Preset sequence of "random" numbers• Same sequence for every function call

• Scaling– To get a random number between 1 and n1 + ( rand() % n )• rand % n returns a number between 0 and n-1• Add 1 to make random number between 1 and n1 + ( rand() % 6) // number between 1 and 6

Page 18: L4 functions

Autumn Semester 2009 Programming and Data Structure 18

Random Number Generation: Contd.

• srand function– Prototype defined in <stdlib.h>– Takes an integer seed - jumps to location in

"random" sequence

srand( seed );

Page 19: L4 functions

Autumn Semester 2009 Programming and Data Structure 19

1 /* A programming example

2 Randomizing die-rolling program */

3 #include <stdlib.h>

4 #include <stdio.h>

5

6 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 }

21

22 return 0;

23 }

Algorithm1. Initialize seed

2. Input value for seed

2.1 Use srand to change random sequence

2.2 Define Loop

3. Generate and output random numbers

Page 20: L4 functions

Autumn Semester 2009 Programming and Data Structure 20

Program Output

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

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

Page 21: L4 functions

Autumn Semester 2009 Programming and Data Structure 21

Another Example: A Game of Chance

• Rules– Roll two dice

• 7 or 11 on first throw, player wins• 2, 3, or 12 on first throw, player loses• 4, 5, 6, 8, 9, 10 - value becomes player's "point"

– Player must roll his point before rolling 7 to win

Page 22: L4 functions

Autumn Semester 2009 Programming and Data Structure 22

Programme Structure

• 1. rollDice prototype•

1.1 Initialize variables•

1.2 Seed srand

• 2. Define switch statement for win/loss/continue

• 2.1 Loop

Page 23: L4 functions

Autumn Semester 2009 Programming and Data Structure 23

1 /* A Game of Chance2 Rolling Two Dice*/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 ) ); /* Randomizing seed by 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

Page 24: L4 functions

Autumn Semester 2009 Programming and Data Structure 24

2.2 Print win/loss

Program Output

33 if ( sum == myPoint ) /* win by making point */

34 gameStatus = 1;

35 else

36 if ( sum == 7 ) /* lose by rolling 7 */

37 gameStatus = 2;

38 }

39

40 if ( gameStatus == 1 )

41 printf( "Player wins\n" );

42 else

43 printf( "Player loses\n" );

44

45 return 0;

46 }

47

48 int rollDice( void )

49 {

50 int die1, die2, workSum;

51

52 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 }

Page 25: L4 functions

Autumn Semester 2009 Programming and Data Structure 25

Program Output

Player 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

Player rolled 6 + 5 = 11Player wins

Page 26: L4 functions

Autumn Semester 2009 Programming and Data Structure 26

Recursion

• A process by which a function calls itself repeatedly.– Either directly.

• X calls X.

– Or cyclically in a chain.• X calls Y, and Y calls X.

• Used for repetitive computations in which each action is stated in terms of a previous result.– fact(n) = n * fact (n-1)

Page 27: L4 functions

Autumn Semester 2009 Programming and Data Structure 27

Contd.

• For a problem to be written in recursive form, two conditions are to be satisfied:– It should be possible to express the problem in

recursive form.– The problem statement must include a

stopping conditionfact(n) = 1, if n = 0

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

Page 28: L4 functions

Autumn Semester 2009 Programming and Data Structure 28

Example 1 :: Factorial

long int fact (n)int n;{ if (n = = 0) return (1); else return (n * fact(n-1));}

Page 29: L4 functions

Autumn Semester 2009 Programming and Data Structure 29

Mechanism of Execution

• When a recursive program is executed, the recursive function calls are not executed immediately.– They are kept aside (on a stack) until the

stopping condition is encountered.– The function calls are then executed in reverse

order.

Page 30: L4 functions

Autumn Semester 2009 Programming and Data Structure 30

Example :: Calculating fact(4)

– First, the function calls will be processed:fact(4) = 4 * fact(3)

fact(3) = 3 * fact(2)

fact(2) = 2 * fact(1)

fact(1) = 1 * fact(0)

– The actual values return in the reverse order:fact(0) = 1

fact(1) = 1 * 1 = 1

fact(2) = 2 * 1 = 2

fact(3) = 3 * 2 = 6

fact(4) = 4 * 6 = 24

Page 31: L4 functions

Autumn Semester 2009 Programming and Data Structure 31

Factorials: Contd.

• Example: factorials– 5! = 5 * 4 * 3 * 2 * 1

– Notice that• 5! = 5 * 4!• 4! = 4 * 3! ...

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

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

Page 32: L4 functions

Autumn Semester 2009 Programming and Data Structure 32

Recursive evaluation of 5!.

Page 33: L4 functions

Autumn Semester 2009 Programming and Data Structure 33

1 /* An example */

2 /* Recursive factorial function */

3 #include <stdio.h>

4

5 long factorial( long number ); /* function prototype */

6

7 /* function main begins program execution */

8 int main( void )

9 {

10 int i; /* counter */

11

12 /* loop 11 times; during each iteration, calculate

13 factorial( i ) and display result */

14 for ( i = 0; i <= 10; i++ ) {

15 printf( "%2d! = %ld\n", i, factorial( i ) );

16 } /* end for */

17

18 return 0; /* indicates successful termination */

19

20 } /* end main */

21

22 /* recursive definition of function factorial */

23 long factorial( long number )

24 {

25 /* base case */

26 if ( number <= 1 ) {

27 return 1;

28 } /* end if */

29 else { /* recursive step */

30 return ( number * factorial( number - 1 ) );

31 } /* end else */

32

33 } /* end function factorial */ 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

TerminatingCriterion

Page 34: L4 functions

Autumn Semester 2009 Programming and Data Structure 34

Another Example :: Fibonacci number

• Fibonacci number f(n) can be defined as: f(0) = 0

f(1) = 1

f(n) = f(n-1) + f(n-2), if n > 1– The successive Fibonacci numbers are:

0, 1, 1, 2, 3, 5, 8, 13, 21, …..

• Function definition:int f (int n){ if (n < 2) return (n); else return (f(n-1) + f(n-2));}

Page 35: L4 functions

Autumn Semester 2009 Programming and Data Structure 35

Tracing Execution

• How many times the function is called when evaluating f(4) ?

• Inefficiency:– Same thing is

computed several times.

f(4)

f(3)

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

f(2)

f(1) f(0)

9 times

Page 36: L4 functions

Autumn Semester 2009 Programming and Data Structure 36

Example Codes: fibonacci()

– Code for the fibonacci functionlong fibonacci( long n ){if (n == 0 || n == 1) // base case

return n;else

return fibonacci( n - 1) + fibonacci( n – 2 );

}

Page 37: L4 functions

Autumn Semester 2009 Programming and Data Structure 37

1 /* Another Example:

2 Recursive fibonacci function */

3 #include <stdio.h>

4

5 long fibonacci( long n ); /* function prototype */

6

7 /* function main begins program execution */

8 int main( void )

9 {

10 long result; /* fibonacci value */

11 long number; /* number input by user */

12

13 /* obtain integer from user */

14 printf( "Enter an integer: " );

15 scanf( "%ld", &number );

16

17 /* calculate fibonacci value for number input by user */

18 result = fibonacci( number );

19

20 /* display result */

21 printf( "Fibonacci( %ld ) = %ld\n", number, result );

22

23 return 0; /* indicates successful termination */

24

25 } /* end main */

26

27 /* Recursive definition of function fibonacci */

28 long fibonacci( long n )

29 {

30 /* base case */

31 if ( n == 0 || n == 1 ) {

32 return n;

33 } /* end if */

34 else { /* recursive step */

35 return fibonacci( n - 1 ) + fibonacci( n - 2 );

36 } /* end else */

37

38 } /* end function fibonacci */

Enter an integer: 0Fibonacci( 0 ) = 0

Enter an integer: 1Fibonacci( 1 ) = 1

Enter an integer: 2Fibonacci( 2 ) = 1 (continued on next slide… )

Page 38: L4 functions

Autumn Semester 2009 Programming and Data Structure 38

(continued from previous slide…) Enter an integer: 3 Fibonacci( 3 ) = 2 Enter an integer: 4 Fibonacci( 4 ) = 3 Enter an integer: 5 Fibonacci( 5 ) = 5 Enter an integer: 6 Fibonacci( 6 ) = 8 )

Page 39: L4 functions

Autumn Semester 2009 Programming and Data Structure 39

Set of recursive calls for fibonacci(3).

Page 40: L4 functions

Autumn Semester 2009 Programming and Data Structure 40

Performance Tip

• Avoid Fibonacci-style recursive programs which result in an exponential “explosion” of calls.

Page 41: L4 functions

Autumn Semester 2009 Programming and Data Structure 41

Recursion and activation records: an example

#include <stdio.h>main(){ int a, b; b = 7; a = xyz (b); printf ("a=%d, b=%d \n", a, b);}

int xyz (int n){ if (n <= 0) return (2); else { n = n - 2; return (xyz(n-1) * xyz(n-2) + 5); }}

What is the output?How many times xyz()Called?

Page 42: L4 functions

Autumn Semester 2009 Programming and Data Structure 42

XYZ(7)

XYZ(4) XYZ(3)

XYZ(1) XYZ(0) XYZ(0) XYZ(-1)

XYZ(-2) XYZ(-3)

2 2

9 2 2 2

239

23*9+5=212

if (n <= 0) return (2); else { n = n - 2; return (xyz(n-1) * xyz(n-2) + 5);}

Page 43: L4 functions

Autumn Semester 2009 Programming and Data Structure 43

Trace of the recursive calls

Page 44: L4 functions

Autumn Semester 2009 Programming and Data Structure 44

RA .. main

-

b = 7

RA .. main

-

b = 7

RA .. xyz

-

n = 4

RA .. xyz

-

n = 1

RA .. main

-

b = 7

RA .. xyz

-

n = 4

RA .. xyz

2

n = -2

RA .. xyz

-

n = 1

RA .. main

-

b = 7

RA .. xyz

-

n = 4

RA .. xyz

2

n = -3

RA .. xyz

-

n = 1

RA .. main

-

b = 7

RA .. xyz

-

n = 4RA .. xyz

9

n = 1

RA .. main

-

b = 7

RA .. xyz

-

n = 4

RA .. main

-

b = 7

RA .. xyz

23

n = 4

RA .. main

-

b = 7

RA .. xyz

-

n = 3

Page 45: L4 functions

Autumn Semester 2009 Programming and Data Structure 45

What is the value of a and b?

How many times the recursive function called?

(i) a=212, b=7

(i) xyz( ) called 9 times

Page 46: L4 functions

Autumn Semester 2009 Programming and Data Structure 46

Recursion vs. Iteration

• Repetition– Iteration: explicit loop– Recursion: repeated function calls

• Termination– Iteration: loop condition fails– Recursion: base case recognized

• Both can have infinite loops• Balance

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

Page 47: L4 functions

Autumn Semester 2009 Programming and Data Structure 48

Performance Tip

• Avoid using recursion in performance situations. Recursive calls take time and consume additional memory.