0% found this document useful (0 votes)
3 views44 pages

CHTP5e 05-Functions 1

This document provides an overview of C programming functions, including how to construct modular programs, utilize the C Standard Library's math functions, and create new functions. It covers function definitions, prototypes, calling conventions, recursion, and error prevention tips. Additionally, it emphasizes good programming practices and software engineering observations to enhance code readability and reusability.

Uploaded by

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

CHTP5e 05-Functions 1

This document provides an overview of C programming functions, including how to construct modular programs, utilize the C Standard Library's math functions, and create new functions. It covers function definitions, prototypes, calling conventions, recursion, and error prevention tips. Additionally, it emphasizes good programming practices and software engineering observations to enhance code readability and reusability.

Uploaded by

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

1

5
C Functions
2

OBJECTIVES
In this chapter you will learn:
 To construct programs modularly from small pieces
called functions.
 The common math functions available in the C
Standard Library.
 To create new functions.
 The mechanisms used to pass information between
functions.
 Simulation techniques using random num­ber
generation.
 How to write and use recursive functions, i.e., functions
that call themselves.
3

5.1 Introduction
5.2 Program Modules in C
5.3 Math Library Functions
5.4 Functions
5.5 Function Definitions
5.6 Function Prototypes
5.7 Function Call Stack and Activation Records
5.8 Headers
5.9 Calling Functions: Call-by-Value and Call-by-
Reference
4

5.10 Random Number Generation


5.11 Example: A Game of Chance
5.12 Storage Classes
5.13 Scope Rules
5.14 Recursion
5.15 Example Using Recursion: Fibonacci Series
5.16 Recursion vs. Iteration
5

5.1 Introduction
 Divide and conquer
– Construct a program from smaller pieces or components
- These smaller pieces are called modules
– Each piece more manageable than the original program
6

5.2 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
 Function calls
– Invoking functions
- Provide function name and arguments (data)
- Function performs operations or manipulations
- Function returns results
– Function call analogy:
- Boss asks worker to complete task
Worker gets information, does task, returns
result
Information hiding: boss does not know
details
7

Good Programming Practice


Familiarize yourself with the rich collection
of functions in the C Standard Library.

Avoid reinventing the wheel. When possible,


use C Standard Library functions instead of
writing new functions. This can reduce
program development time.
Using the functions in the C Standard Library
helps make programs more portable.
8

5.3 Math Library Functions


 Math library functions
– perform common mathematical calculations
– #include <math.h>
 Format for calling functions
– FunctionName( argument );
- If multiple arguments, use comma-separated list
– printf( "%.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
9

Error-Prevention Tip

Include the math header by using the


preprocessor directive #include <math.h>
when using functions in the math library.
10

Function Description Example

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0


sqrt( 9.0 ) is 3.0

exp( x ) exponential function ex exp( 1.0 ) is 2.718282


exp( 2.0 ) is 7.389056

log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0


log( 7.389056 ) is 2.0

log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0


log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0

fabs( x ) absolute value of x fabs( 5.0 ) is 5.0


fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0

ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0


not less than x ceil( -9.8 ) is -9.0

Commonly used math library functions. (Part 1 of 2.)


11

Function Description Example

floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0


not greater than x
floor( -9.8 ) is -10.0

pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0


pow( 9, .5 ) is 3.0

fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992


point number

sin( x ) trigonometric sine of x sin( 0.0 ) is 0.0


(x in radians)

cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0


(x in radians)

tan( x ) trigonometric tangent of x tan( 0.0 ) is 0.0


(x in radians)

Commonly used math library functions. (Part 2 of 2.)


12

5.4 Functions
 Functions
– Modularize a program
– All variables defined inside functions are local variables
- Known only in function defined
– Parameters
- Communicate information between functions
- Local variables
 Benefits of functions
– Divide and conquer
- Manageable program development
– Software reusability
- Use existing functions as building blocks for new programs
- Abstraction - hide internal details (library functions)
– Avoid code repetition
13

Software Engineering Observation

In programs containing many functions,


main is often implemented as a group of
calls to functions that perform the bulk of
the program’s work.

Each function should be limited to


performing a single, well-defined task, and
the func­tion name should effectively express
that task. This facilitates abstraction and
promotes software reusability.
14

Software Engineering Observation

If you cannot choose a concise name that


expresses what the function does, it is
possible that your function is attempting to
perform too many diverse tasks. It is usually
best to break such a function into several
smaller functions.

Place a blank line between function


definitions to separate the functions and
enhance program readability.
15

5.5 Function Definitions


 Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
- void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares parameters
- A type must be listed explicitly for each parameter unless, the
parameter is of type int
16

5.5 Function Definitions


 Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Definitions and statements: function body (block)
- Variables can be defined inside blocks (can be nested)
- Functions can not be defined inside other functions
– Returning control
- If nothing returned
return;
or, until reaches right brace
- If something returned
return expression;
1 /* Fig. 5.3: fig05_03.c 17
2 Creating and using a programmer-defined function */
3 #include <stdio.h>
4
5 int square( int y ); /* function prototype */
6
7 /* function main begins program execution */
8 int main( void ) Function prototype indicates function will
9 { be defined later in the program
10 int x; /* counter */
11
12 /* loop 10 times and calculate and output square of x each time */
13 for ( x = 1; x <= 10; x++ ) {
14 printf( "%d ", square( x ) ); /* function call */
15 } /* end for */
16
Call to square function
17 printf( "\n" );
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
22
23 /* square function definition returns square of parameter */
24 int square( int y ) /* y is a copy of argument to function */
Function definition
25 {
26 return y * y; /* returns square of y as an int */
27
28 } /* end function square */

1 4 9 16 25 36 49 64 81 100
18

Common Programming Error


Omitting the return-value-type in a function
definition is a syntax error if the function
prototype specifies a return type other than int.

Forgetting to return a value from a function


that is supposed to return a value can lead to
unexpected errors. The C standard states that
the result of this omission is undefined.

Returning a value from a function with a


void return type is a syntax error.
19

Good Programming Practice

Even though an omitted return type defaults to


int, always state the return type explicitly.
20

Common Programming Error


Specifying function parameters of the same type as
double x, y instead of double x, double y might
cause errors, declaration double x, y makes y a
parameter of type int because int is the default.

Placing a semicolon after the right parenthesis


enclosing the parameter list of a function definition
is a syntax error.

Defining a function parameter again as a local


variable within the function is a syntax error.
21

Good Programming Practice

Include the type of each parameter in the


parameter list, even if that parameter is of the
default type int.

Choosing meaningful function names and


meaningful parameter names makes programs
more readable and helps avoid excessive use of
comments.
22

Common Programming Error


Defining a function inside another function is a
syntax error.

Although it is not incorrect to do so, do not use the


same names for the arguments passed to a function
and the corresponding parameters in the function
definition. This helps avoid ambiguity.
23

Software Engineering Observation


A function should generally be no longer than one
page. Better yet, functions should generally be no
longer than half a page. Small functions promote
software reusability.

Programs should be written as collections of small


functions. This makes programs easier to write,
debug, maintain and modify.
24

Software Engineering Observation


A function requiring a large number of
parameters may be performing too many tasks.
Consider dividing the function into smaller
functions that perform the separate tasks. The
function header should fit on one line if possible.

The function prototype, function header and


function calls should all agree in the number,
type, and order of arguments and parameters,
and in the type of return value.
1 /* Fig. 5.4: fig05_04.c 25
2 Finding the maximum of three integers */
3 #include <stdio.h>
4
5 int maximum( int x, int y, int z ); /* function prototype */
6
7 /* function main begins program execution */ Function prototype
8 int main( void )
9 {
10 int number1; /* first integer */
11 int number2; /* second integer */
12 int number3; /* third integer */
13
14 printf( "Enter three integers: " );
15 scanf( "%d%d%d", &number1, &number2, &number3 ); Function call
16
17 /* number1, number2 and number3 are arguments
18 to the maximum function call */
19 printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
24
25 /* Function maximum definition */ 26
26 /* x, y and z are parameters */
27 int maximum( int x, int y, int z ) Function definition
28 {
29 int max = x; /* assume x is largest */
30
31 if ( y > max ) { /* if y is larger than max, assign y to max */
32 max = y;
33 } /* end if */
34
35 if ( z > max ) { /* if z is larger than max, assign z to max */
36 max = z;
37 } /* end if */
38
39 return max; /* max is largest value */
40
41 } /* end function maximum */

Enter three integers: 22 85 17


Maximum is: 85

Enter three integers: 85 22 17


Maximum is: 85

Enter three integers: 22 17 85


Maximum is: 85
27

5.6 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
program
– The function with the prototype
int maximum( int x, int y, int z );
- Takes in 3 ints
- Returns an int
 Promotion rules and conversions
– Converting to lower types can lead to errors
28

Good Programming Practice


Include function prototypes for all functions to take
advantage of C’s type-checking capabilities. Use
#include preprocessor directives to obtain function
prototypes for the standard library functions from
the headers for the appropriate libraries, or to obtain
headers containing function prototypes for functions
developed by you and/or your group members.

Parameter names are sometimes included in function


prototypes (our preference) for documentation
purposes. The compiler ignores these names.
29

printf conversion scanf conversion


Data type
specification specification

Long double %Lf %Lf


double %f %lf
float %f %f
Unsigned long int %lu %lu
long int %ld %ld

unsigned int %u %u
int %d %d
unsigned short %hu %hu
short %hd %hd
char %c %c

Promotion hierarchy for data types.


30

Common Programming Error


Forgetting the semicolon at the end of a function
prototype is a syntax error.

Converting from a higher data type in the promotion


hierarchy to a lower type can change the data value.

Forgetting a function prototype causes a syntax error


if the return type of the function is not int and the
function definition appears after the function call in
the program. Otherwise, forgetting a function
prototype may cause a runtime error or an unexpected
result.
31

5.7 Function Call Stack and Activation


Records
 Program execution stack
– A stack is a last-in, first-out (LIFO) data structure
- Anything put into the stack is placed “on top”
- The only data that can be taken out is the data on top
– C uses a program execution stack to keep track of which
functions have been called
- When a function is called, it is placed on top of the stack
- When a function ends, it is taken off the stack and control
returns to the function immediately below it
– Calling more functions than C can handle at once is known
as a “stack overflow error”
32

5.8 Headers
 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
33

Standard library header Explanation

<assert.h> Contains macros and information for adding diagnostics that aid
program debugging.
<ctype.h> Contains function prototypes for functions that test characters for
certain properties, and function prototypes for functions that can
be used to convert lowercase letters to uppercase letters and vice
versa.
<errno.h> Defines macros that are useful for reporting error conditions.
<float.h> Contains the floating-point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<locale.h> Contains function prototypes and other information that enables a
program to be modified for the current locale on which it is
running. The notion of locale enables the computer system to
handle different conventions for expressing data like dates, times,
dollar amounts and large numbers throughout the world.

Some of the standard library headers. (Part 1 of 3.)


34

Standard library header Explanation

<math.h> Contains function prototypes for math library functions.


<setjmp.h> Contains function prototypes for functions that allow bypassing of
the usual function call and return sequence.
<signal.h> Contains function prototypes and macros to handle various
conditions that may arise during program execution.
<stdarg.h> Defines macros for dealing with a list of arguments to a function
whose number and types are unknown.
<stddef.h> Contains common definitions of types used by C for performing
certain calculations.

Some of the standard library headers


35

Standard library header Explanation

<stdio.h> Contains function prototypes for the standard input/output library


functions, and information used by them.
<stdlib.h> Contains function prototypes for conversions of numbers to text
and text to numbers, memory allocation, random numbers, and
other utility functions.
<string.h> Contains function prototypes for string-processing functions.
<time.h> Contains function prototypes and types for manipulating the time
and date.

Some of the standard library headers.


36

5.9 Calling Functions: Call-by-Value and


Call-by-Reference
 Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
- Avoids accidental changes
 Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
 For now, we focus on call by value
37

5.10 Random Number Generation


 rand function
– Load <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 n
1 + ( rand() % n )
- rand() % n returns a number between 0 and n - 1
- Add 1 to make random number between 1 and n
1 + ( rand() % 6)
number between 1 and 6
1 /* Fig. 5.7: fig05_07.c 38
2 Shifted, scaled integers produced by 1 + rand() % 6 */
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 /* function main begins program execution */
7 int main( void )
8 {
9 int i; /* counter */
10
11 /* loop 20 times */
12 for ( i = 1; i <= 20; i++ ) {
13
14 /* pick random number from 1 to 6 and output it */
15 printf( "%10d", 1 + ( rand() % 6 ) );
16
Generates a random number between 1 and 6
17 /* if counter is divisible by 5, begin new line of output */
18 if ( i % 5 == 0 ) {
19 printf( "\n" );
20 } /* end if */
21
22 } /* end for */
23
24 return 0; /* indicates successful termination */
25
26 } /* end main */
6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1
1 /* Fig. 5.8: fig05_08.c 39
2 Roll a six-sided die 6000 times */
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 /* function main begins program execution */
7 int main( void )
8 {
9 int frequency1 = 0; /* rolled 1 counter */
10 int frequency2 = 0; /* rolled 2 counter */
11 int frequency3 = 0; /* rolled 3 counter */
12 int frequency4 = 0; /* rolled 4 counter */
13 int frequency5 = 0; /* rolled 5 counter */
14 int frequency6 = 0; /* rolled 6 counter */
15
16 int roll; /* roll counter, value 1 to 6000 */
17 int face; /* represents one roll of the die, value 1 to 6 */
18
19 /* loop 6000 times and summarize results */
20 for ( roll = 1; roll <= 6000; roll++ ) {
21 face = 1 + rand() % 6; /* random number from 1 to 6 */
22
23 /* determine face value and increment appropriate counter */
24 switch ( face ) {
25
26 case 1: /* rolled 1 */
27 ++frequency1;
28 break;
29
30 case 2: /* rolled 2 */ 40
31 ++frequency2;
32 break;
33
34 case 3: /* rolled 3 */
35 ++frequency3;
36 break;
37
38 case 4: /* rolled 4 */
39 ++frequency4;
40 break;
41
42 case 5: /* rolled 5 */
43 ++frequency5;
44 break;
45
46 case 6: /* rolled 6 */
47 ++frequency6;
48 break; /* optional */
49 } /* end switch */
50
51 } /* end for */
52
53 /* display results in tabular format */ 41
54 printf( "%s%13s\n", "Face", "Frequency" );
55 printf( " 1%13d\n", frequency1 );
56 printf( " 2%13d\n", frequency2 );
57 printf( " 3%13d\n", frequency3 );
58 printf( " 4%13d\n", frequency4 );
59 printf( " 5%13d\n", frequency5 );
60 printf( " 6%13d\n", frequency6 );
61
62 return 0; /* indicates successful termination */
63
64 } /* end main */

Face Frequency
1 1003
2 1017
3 983
4 994
5 1004
6 999
42

5.10 Random Number Generation


 srand function
– <stdlib.h>
– Takes an integer seed and jumps to that location in its
"random" sequence
srand( seed );
– srand( time( NULL ) );/*load <time.h> */
- time( NULL )
Returns the number of seconds that have
passed since January 1, 1970
“Randomizes" the seed
1 /* Fig. 5.9: fig05_09.c 43
2 Randomizing die-rolling program */
3 #include <stdlib.h>
4 #include <stdio.h>
5
6 /* function main begins program execution */
7 int main( void )
8 {
9 int i; /* counter */
10 unsigned seed; /* number used to seed random number generator */
11
12 printf( "Enter seed: " );
13 scanf( "%u", &seed ); /* note %u for unsigned */
14
15 srand( seed ); /* seed random number generator */ Seeds the rand function
16
17 /* loop 10 times */
18 for ( i = 1; i <= 10; i++ ) {
19
20 /* pick a random number from 1 to 6 and output it */ 44
21 printf( "%10d", 1 + ( rand() % 6 ) );
22
23 /* if counter is divisible by 5, begin a new line of output */
24 if ( i % 5 == 0 ) {
25 printf( "\n" );
26 } /* end if */
27
28 } /* end for */
29
30 return 0; /* indicates successful termination */
31
32 } /* end main */

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

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

You might also like