0% found this document useful (0 votes)
9 views9 pages

1.10 Functions

Chapter 5 discusses functions in C programming, emphasizing their role in modularizing programs and managing complexity through divide and conquer strategies. It covers function definitions, prototypes, calling conventions (call by value and call by reference), and includes examples such as a game of chance and random number generation. Additionally, it touches on storage classes and recursion, providing a comprehensive overview of how functions enhance code reusability and maintainability.

Uploaded by

carllongs1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

1.10 Functions

Chapter 5 discusses functions in C programming, emphasizing their role in modularizing programs and managing complexity through divide and conquer strategies. It covers function definitions, prototypes, calling conventions (call by value and call by reference), and includes examples such as a game of chance and random number generation. Additionally, it touches on storage classes and recursion, providing a comprehensive overview of how functions enhance code reusability and maintainability.

Uploaded by

carllongs1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

4/28/2022

Chapter 5 - Functions 5.1 Introduction

Outline
5.1 Introduction • Divide and conquer
5.2 Program Modules in C
5.3 Math Library Functions
5.4 Functions – Construct a program from smaller pieces or components
5.5 Function Definitions
5.6 Function Prototypes • These smaller pieces are called modules
5.7 Header Files
5.8 Calling Functions: Call by Value and Call by Reference
5.9 Random Number Generation – Each piece more manageable than the original program
5.10 Example: A Game of Chance
5.11 Storage Classes
5.12 Scope Rules
5.13 Recursion
5.14 Example Using Recursion: The Fibonacci Series
5.15 Recursion vs. Iteration

 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.


All rights reserved. All rights reserved.

5.2 Program Modules in C 5.4 Functions


• Functions • Functions
– Modules in C – Modularize a program
– Programs combine user-defined functions with library functions – All variables declared inside functions are local variables
• C standard library has a wide variety of functions • Known only in function defined
• Function calls – Parameters
• Communicate information between functions
– Invoking functions
• Local variables
• Provide function name and arguments (data)
• Benefits of functions
• Function performs operations or manipulations
– Divide and conquer
• Function returns results • Manageable program development
– Function call analogy: – Software reusability
• Boss asks worker to complete task • Use existing functions as building blocks for new programs
– Worker gets information, does task, returns result • Abstraction - hide internal details (library functions)
– Information hiding: boss does not know details – Avoid code repetition
 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

1
4/28/2022

5.5 Function Definitions 5.5 Function Definitions


• Function definition format • Function definition format (continued)
return-value-type function-name( parameter-list ) return-value-type function-name( parameter-list )
{ {
declarations and statements declarations and statements
} }
– Function-name: any valid identifier – Declarations and statements: function body (block)
– Return-value-type: data type of the result (default int) • Variables can be declared inside blocks (can be nested)
• void – indicates that the function returns nothing • Functions can not be defined inside other functions
– Parameter-list: comma separated list, declares parameters – Returning control
• A type must be listed explicitly for each parameter unless, the • If nothing returned
parameter is of type int – return;
– or, until reaches right brace
• If something returned
– return expression;
 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

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


int main() int main()
{ {
int a, b, c, largest; int a, b, c, largest;
printf( "Enter the three integers: " ); printf( "Enter the three integers: " );
scanf( "%d%d%d", &a, &b, &c ); scanf( "%d%d%d", &a, &b, &c );

largest = maximum( a, b, c ); maximum( a, b, c );

printf( "Maximum is: %d\n", largest); return 0;


return 0; }
} int maximum( int x, int y, int z )
int maximum( int x, int y, int z ) { int max = x;
{ int max = x; if ( y > max )
if ( y > max ) max = y;
max = y; if ( z > max )
if ( z > max ) max = z;
max = z; printf( "Maximum is: %d\n", max);
return max;
}  2000 Prentice Hall, Inc. return max;  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.
}

2
4/28/2022

1 /* Fig. 5.4: fig05_04.c


2 Finding the maximum of three integers */ Outline
Exercise 3
4
#include <stdio.h>

5 int maximum( int, int, int ); /* function prototype */ 1. Function prototype


6 (3 parameters)
7 int main()
Write a C program to find the sum and the product of two 8 {
9 int a, b, c; 2. Input values
10
matrices of order 2 by 2 using multidimensional arrays 11 printf( "Enter three integers: " );
12 scanf( "%d%d%d", &a, &b, &c ); 2.1 Call function
13 printf( "Maximum is: %d\n", maximum( a, b, c ) );
where the elements of each matrix are entered by the user. 14
15 return 0; 3. Function definition
16 }

The program should consist of the following: 17


18 /* Function maximum definition */
19 int maximum( int x, int y, int z )
20 {
a) A function (f_sum) to compute the sum of the matrices 21
22
int max = x;

23 if ( y > max )
24 max = y;
b) A function (f_prod) to compute the product of the two 25
26 if ( z > max )
27 max = z;
matrices 28
29 return max;
30 }
Enter three integers: 22 85 17
 2000 Prentice Hall, Inc. Maximum is: 85 Program Output
 2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

5.6 Function Prototypes 5.7 Header Files


• Function prototype • Header files
– Function name – Contain function prototypes for library functions
– Parameters – what the function takes in – <stdlib.h> , <math.h> , etc
– Return type – data type function returns (default int) – Load with #include <filename>
– Used to validate functions #include <math.h>
– Prototype only needed if function definition comes after use • Custom header files
in program – Create file with functions
– The function with the prototype – Save as filename.h
int maximum( int, int, int );
– Load in other files with #include "filename.h"
• Takes in 3 ints
– Reuse functions
• Returns an int
• Promotion rules and conversions
– Converting to lower types can lead to errors
 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

3
4/28/2022

5.8 Calling Functions: Call by Value and


5.9 Random Number Generation
Call by Reference
• Used when invoking functions • rand function
– Load <stdlib.h>
• Call by value
– Returns "random" number between 0 and RAND_MAX (at
– Copy of argument passed to function least 32767)
– Changes in function do not effect original i = rand();
– Use when function does not need to modify argument – Pseudorandom
• Avoids accidental changes • Preset sequence of "random" numbers
• Same sequence for every function call
• Call by reference
– Passes original argument
• Scaling
– To get a random number between 1 and n
– Changes in function effect original 1 + ( rand() % n )
– Only used with trusted functions • rand() % n returns a number between 0 and n - 1
• For now, we focus on call by value • Add 1 to make random number between 1 and n
1 + ( rand() % 6)
– number between 1 and 6
 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

1 /* Fig. 5.9: fig05_09.c


2 Randomizing die-rolling program */ Outline
5.9 Random Number Generation 3 #include <stdlib.h>
4 #include <stdio.h> 1. Initialize seed

• srand function 5
6 int main() 2. Input value for seed
– <stdlib.h> 7 {
2.1 Use srand to
– Takes an integer seed and jumps to that location in its 8 int i;
9 unsigned seed; change random
"random" sequence 10
sequence
srand( seed ); 11 printf( "Enter seed: " );
2.2 Define Loop
– srand( time( NULL ) ); //load <time.h> 12 scanf( "%u", &seed );
13 srand( seed );
• time( NULL ) 3. Generate and
14
– Returns the time at which the program was compiled in 15 for ( i = 1; i <= 10; i++ ) {
output random
seconds numbers
16 printf( "%10d", 1 + ( rand() % 6 ) );

– “Randomizes" the seed 17


18 if ( i % 5 == 0 )
19 printf( "\n" );
20 }
21
22 return 0;
23 }
 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

4
4/28/2022

Enter seed: 67
6 1 4 6 2
Outline
1 6 1 6 4 5.10 Example: A Game of Chance
Program Output
Enter seed: 867
2
1
4
1
6
3
1
6
6
2
• Craps simulator
• Rules
Enter seed: 67
6 1 4 6 2 – Roll two dice
1 6 1 6 4
• 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

 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.


All rights reserved. All rights reserved.

1 /* Fig. 5.10: fig05_10.c 33 if ( sum == myPoint ) /* win by making point */


2 Craps */ Outline 34 gameStatus = 1; Outline
3 #include <stdio.h> 35 else
4 #include <stdlib.h> 36 if ( sum == 7 ) /* lose by rolling 7 */
5 #include <time.h> 1. rollDice 2.2 Print win/loss
37 gameStatus = 2;
6 prototype
38 }
7 int rollDice( void );
39
8
1.1 Initialize variables 40 if ( gameStatus == 1 )
9 int main()
10 { 41 printf( "Player wins\n" );
11 int gameStatus, sum, myPoint; 1.2 Seed srand 42 else
12 43 printf( "Player loses\n" );
13 srand( time( NULL ) ); 44
14 sum = rollDice(); /* first roll of the dice */ 2. Define switch
45 return 0;
15 statement for 46 }
16 switch ( sum ) { win/loss/continue 47
17 case 7: case 11: /* win on first roll */
48 int rollDice( void )
18 gameStatus = 1;
19 break; 2.1 Loop 49 {
20 case 2: case 3: case 12: /* lose on first roll */ 50 int die1, die2, workSum;
21 gameStatus = 2; 51
22 break; 52 die1 = 1 + ( rand() % 6 );
23 default: /* remember point */ 53 die2 = 1 + ( rand() % 6 );
24 gameStatus = 0; 54 workSum = die1 + die2;
25 myPoint = sum; 55 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum );
26 printf( "Point is %d\n", myPoint );
56 return workSum;
27 break;
28 } 57 }
29 Player rolled 6 + 5 = 11
Player wins Program Output
30 while ( gameStatus == 0 ) { /* keep rolling */
31 sum = rollDice();  2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
32 All rights reserved. All rights reserved.

5
4/28/2022

Player rolled 6 + 6 = 12
Player loses
Outline
Player rolled 4 + 6 = 10 5.11 Storage Classes
Point is 10 Program Output
Player rolled 2 + 4 = 6
Player rolled
Player rolled
6
3
+
+
5
3
=
=
11
6 • Storage class specifiers
Player rolled 6 + 4 = 10
Player wins – Storage duration – how long an object exists in memory
Player rolled 1 + 3 = 4 – Scope – where object can be referenced in program
Point is 4
Player rolled 1 + 4 = 5 – Linkage – specifies the files in which an identifier is known
Player rolled 5 + 4 = 9
Player rolled 4 + 6 = 10 (more in Chapter 14)
Player rolled 6 + 3 = 9
Player rolled
Player rolled
1
5
+
+
2
2
=
=
3
7
• Automatic storage
Player loses
– Object created and destroyed within its block
– auto: default for local variables
auto double x, y;
– register: tries to put variable into high-speed registers
• Can only be used for automatic variables
register int counter = 1;

 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.


All rights reserved. All rights reserved.

5.11 Storage Classes 5.12 Scope Rules


• Static storage • File scope
– Variables exist for entire program execution – Identifier defined outside function, known in all functions
– Default value of zero – Used for global variables, function definitions, function
– static: local variables defined in functions. prototypes
• Keep value after function ends • Function scope
• Only known in their own function – Can only be referenced inside a function body
– extern: default for global variables and functions – Used only for labels (start:, case: , etc.)
• Known in any function

 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.


All rights reserved. All rights reserved.

6
4/28/2022

1 /* Fig. 5.12: fig05_12.c


2 A scoping example */ Outline
5.12 Scope Rules 3
4
#include <stdio.h>

5 void a( void ); /* function prototype */ 1. Function prototypes

• Block scope 6
7
void b( void );
void c( void );
/* function prototype */
/* function prototype */
1.1 Initialize global
8
– Identifier declared inside a block 9 int x = 1; /* global variable */
variable

• Block scope begins at declaration, ends at right brace 10


11 int main() 1.2 Initialize local
– Used for variables, function parameters (local variables of 12 { variable
13 int x = 5; /* local variable to main */
function) 14
1.3 Initialize local
– Outer blocks "hidden" from inner blocks if there is a variable 15
16
printf("local x in outer scope of main is %d\n", x );
variable in block
with the same name in the inner block 17 { /* start new scope */
18 int x = 7;
2. Call functions
• Function prototype scope 19
20 printf( "local x in inner scope of main is %d\n", x );
– Used for identifiers in parameter list 21 } /* end new scope */ 3. Output results
22
23 printf( "local x in outer scope of main is %d\n", x );
24
25 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 */
 2000 Prentice Hall, Inc. 30 c(); /* global x also retains its value */  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

31
32 printf( "local x in main is %d\n", x ); Outline local x in outer scope of main is 5
Outline
33 return 0;
local x in inner scope of main is 7
34 } local x in outer scope of main is 5
35
3.1 Function Program Output
36 void a( void ) definitions local x in a is 25 after entering a
local x in a is 26 before exiting a
37 {
38 int x = 25; /* initialized each time a is called */ local static x is 50 on entering b
39 local static x is 51 on exiting b
40 printf( "\nlocal x in a is %d after entering a\n", x );
global x is 1 on entering c
41 ++x;
global x is 10 on exiting c
42 printf( "local x in a is %d before exiting a\n", x );
43 } local x in a is 25 after entering a
44 local x in a is 26 before exiting a
45 void b( void )
local static x is 51 on entering b
46 { local static x is 52 on exiting b
47 static int x = 50; /* static initialization only */
48 /* first time b is called */ global x is 10 on entering c
global x is 100 on exiting c
49 printf( "\nlocal static x is %d on entering b\n", x );
local x in main is 5
50 ++x;
51 printf( "local static x is %d on exiting b\n", x );
52 }
53
54 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 }  2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

7
4/28/2022

5.13 Recursion 5.13 Recursion


• Recursive functions • Example: factorials
– Functions that call themselves – 5! = 5 * 4 * 3 * 2 * 1
– Can only solve a base case – Notice that
– Divide a problem up into • 5! = 5 * 4!
• What it can do • 4! = 4 * 3! ...
• What it cannot do – Can compute factorials recursively
– What it cannot do resembles original problem – Solve base case (1! = 0! = 1) then plug in
– The function launches a new copy of itself (recursion step) • 2! = 2 * 1! = 2 * 1 = 2;
to solve what it cannot do • 3! = 3 * 2! = 3 * 2 = 6;
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem

 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.


All rights reserved. All rights reserved.

5.14 Example Using Recursion: The 5.14 Example Using Recursion: The
Fibonacci Series Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8... • Set of recursive calls to function fibonacci
– Each number is the sum of the previous two
f( 3 )
– Can be solved recursively:
• fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the fibaonacci function
return f( 2 ) + f( 1 )
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case return f( 1 ) + f( 0 ) return 1
return n;
else
return fibonacci( n - 1) + return 1 return 0
fibonacci( n – 2 );
}

 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.


All rights reserved. All rights reserved.

8
4/28/2022

1 /* Fig. 5.15: fig05_15.c Enter an integer: 2


2 Recursive fibonacci function */ Outline Fibonacci(2) = 1
Outline
3 #include <stdio.h>
Enter an integer: 3
4 Fibonacci(3) = 2
5 long fibonacci( long ); 1. Function prototype Program Output
6 Enter an integer: 4
7 int main() Fibonacci(4) = 3
1.1 Initialize variables
8 {
Enter an integer: 5
9 long result, number; Fibonacci(5) = 5
10 2. Input an integer
11 printf( "Enter an integer: " ); Enter an integer: 6
12 scanf( "%ld", &number ); Fibonacci(6) = 8
13 result = fibonacci( number );
2.1 Call function
fibonacci Enter an integer: 10
14 printf( "Fibonacci( %ld ) = %ld\n", number, result ); Fibonacci(10) = 55
15 return 0;
16 } Enter an integer: 20
2.2 Output results. Fibonacci(20) = 6765
17
18 /* Recursive definition of function fibonacci */ Enter an integer: 30
19 long fibonacci( long n ) 3. Define fibonacci Fibonacci(30) = 832040
20 { recursively
21 if ( n == 0 || n == 1 ) Enter an integer: 35
Fibonacci(35) = 9227465
22 return n;
23 else
24 return fibonacci( n - 1 ) + fibonacci( n - 2 );
25 }
Enter an integer: 0
Fibonacci(0) = 0 Program Output

Enter an integer: 1
Fibonacci(1) = 1
 2000 Prentice Hall, Inc.  2000 Prentice Hall, Inc.
All rights reserved. All rights reserved.

5.15 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)

 2000 Prentice Hall, Inc.


All rights reserved.

You might also like