Functions
Shivani Varshney/RCET/Programming with C
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
Shivani Varshney/RCET/Programming with C
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
Shivani Varshney/RCET/Programming with C
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
Shivani Varshney/RCET/Programming with C
Functions
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 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
Shivani Varshney/RCET/Programming with C
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
Shivani Varshney/RCET/Programming with C
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)
Functions can not be defined inside other functions
Returning control
If nothing returned
return;
or, until reaches right brace
If something returned
return expression;
Shivani Varshney/RCET/Programming with C
1 /* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */
3 #include <stdio.h>
4
5 int maximum( int, int, int ); /* function prototype */ 1. Function prototype (3
6 parameters)
7 int main()
8 {
2. Input values
9 int a, b, c;
10
11 printf( "Enter three integers: " ); 2.1 Call function
12 scanf( "%d%d%d", &a, &b, &c );
13 printf( "Maximum is: %d\n", maximum( a, b, c ) );
14
15 return 0; 3. Function definition
16 }
17
18 /* Function maximum definition */
19 int maximum( int x, int y, int z )
20 {
21 int max = x;
22
23 if ( y > max )
24 max = y;
25
26 if ( z > max )
27 max = z;
28
29 return max;
30 }
Enter three integers: 22 85 17 Program Output
Maximum is: 85
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, int, int );
Takes in 3 ints
Returns an int
Promotion rules and conversions
Converting to lower types can lead to errors
Shivani Varshney/RCET/Programming with C
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
Shivani Varshney/RCET/Programming with C
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 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
Shivani Varshney/RCET/Programming with C
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
Shivani Varshney/RCET/Programming with C
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 time at which the program was compiled in seconds
“Randomizes" the seed
Shivani Varshney/RCET/Programming with C
1 /* Fig. 5.9: fig05_09.c
2 Randomizing die-rolling program */
3 #include <stdlib.h>
4 #include <stdio.h> 1. Initialize seed
5
6 int main() 2. Input value for seed
7 {
8 int i; 2.1 Use srand to change
9 unsigned seed; random sequence
10
11 printf( "Enter seed: " ); 2.2 Define Loop
12 scanf( "%u", &seed );
13 srand( seed ); 3. Generate and output
14 random numbers
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 }
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
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
Storage Classes
Storage class specifiers
Storage duration – how long an object exists in memory
Scope – where object can be referenced in program
Linkage – specifies the files in which an identifier is known
(more in Chapter 14)
Automatic storage
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;
Shivani Varshney/RCET/Programming with C
Storage Classes
Static storage
Variables exist for entire program execution
Default value of zero
static: local variables defined in functions.
Keep value after function ends
Only known in their own function
extern: default for global variables and functions
Known in any function
Shivani Varshney/RCET/Programming with C
Scope Rules
File scope
Identifier defined outside function, known in all functions
Used for global variables, function definitions, function
prototypes
Function scope
Can only be referenced inside a function body
Used only for labels (start:, case: , etc.)
Shivani Varshney/RCET/Programming with C
Scope Rules
Block scope
Identifier declared inside a block
Block scope begins at declaration, ends at right brace
Used for variables, function parameters (local variables of
function)
Outer blocks "hidden" from inner blocks if there is a variable
with the same name in the inner block
Function prototype scope
Used for identifiers in parameter list
Shivani Varshney/RCET/Programming with C
1 /* Fig. 5.12: fig05_12.c
2 A scoping example */
3 #include <stdio.h>
4
5 void a( void ); /* function prototype */
1. Function prototypes
6 void b( void ); /* function prototype */
7 void c( void ); /* function prototype */ 1.1 Initialize global
8 variable
9 int x = 1; /* global variable */
10
11 int main() 1.2 Initialize local
12 { variable
13 int x = 5; /* local variable to main */
14
15 printf("local x in outer scope of main is %d\n", x ); 1.3 Initialize local
16 variable in block
17 { /* start new scope */
18 int x = 7;
2. Call functions
19
20 printf( "local x in inner scope of main is %d\n",
x ); }
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 c();
30 */ /* global x also retains its value */
31
32 printf( "local x in main is %d\n", x );
33 return 0;
34 }
3.1 Function definitions
35
36 void a( void )
37 {
38 int x = 25; /* initialized each time a is called */
39
40 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 }
44
45 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 }
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 }
local x in outer scope of main is 5
local x in inner scope of main is 7 Program Output
local x in outer scope of main is 5
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 50 on entering b
local static x is 51 on exiting b
global x is 1 on entering c
global x is 10 on exiting c
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 51 on entering b
local static x is 52 on exiting b
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5
Pointers as function arguments
We can pass the address of a variable as an argument
to a function.
When we pass addresses to a function, the parameters
receiving the addresses should be pointers.
The process of calling a function using pointers to pass
the addresses of variables is known as call by
reference.
The function which is called by reference can change
the value of the variable used in the call.
This mechanism is also known as call by address or
pass by pointers.
Shivani Varshney/RCET/Programming with C
1. The function parameters are declared as pointers.
2. The dereferencing pointers are used in the
function body.
3. When the function is called, the addresses are
passed as actual arguments.
Shivani Varshney/RCET/Programming with C
Passing array to function
One dimensional arrays :
To pass a one-dimensional array to a called function, it is sufficient to
list the name of the array, without any subscripts and the size of the
array as arguments.
For example :
Declaration : void largest(int [ ],int);
Calling : largest(a,n)
Definition : void largest(int a[ ],int n)
{
Shivani Varshney/RCET/Programming with C
Three rules to pass an array to a function
The function must be called by passing only the name of the array.
for example : largest(a);
In the function definition, the formal parameter must be an array
type, the size of the array does not need to be specified.
for example : void largest(int a[ ])
{
}
The function prototype must show that the argument is an array.
for example : void largest(int [ ]);
Shivani Varshney/RCET/Programming with C
Two Dimensional Array
The rules are :
The function must be called by passing only the array name.
for example : average(matrix,m,n);
In the function definition, we must indicate that the array has two
dimensions by including two sets of brackets.
for example : void average(int matrix[ ][n],int m,int n)
{
}
The size of the second dimension must be specified.
The prototype declaration should be similar to function header.
for example : void average(int matrix[ ][n],int,int);
Shivani Varshney/RCET/Programming with C
Passing strings to functions
The string to be passed must be declared as a formal argument
of the function when it is defined.
for example : void display(char str[ ])
{
}
The function prototype must show that the argument is a string
void display(char str[ ]);
A call to the function must have a string array name without
subscripts as its actual argument.
display(str);
Shivani Varshney/RCET/Programming with C
Using Library Functions
Shivani Varshney/RCET/Programming with C
Standard Library Function Prototypes
Any standard library function used by your program must
be prototyped.
Appropriate header for each library function has to be
used.
All necessary headers are provided by the C compiler.
The library headers are (usually) files that use the .h
extension.
A header contains two main elements: any definitions used
by the library functions and the prototypes for the library
functions.
Shivani Varshney/RCET/Programming with C
For example, <stdio.h> is included in almost all programs
because it contains the prototype for printf( ).
Shivani Varshney/RCET/Programming with C
Macro Definitions
Shivani Varshney/RCET/Programming with C
The #define directive has another powerful feature:
The macro name can have arguments. Each time the
macro name is encountered, the arguments used in
its definition are replaced by the actual arguments
found in the program. This form of a macro is called
a function-like macro.
Shivani Varshney/RCET/Programming with C
Example
#include <stdio.h>
#define ABS(a) (a) < 0 ? -(a) : (a)
int main(void)
{
printf("abs of -1 and 1: %d %d", ABS(-1), ABS
(1));
return 0;
}
Shivani Varshney/RCET/Programming with C
When this program is compiled, a in the macro
definition will be substituted with the values –1 and
1. The parentheses that enclose a ensure proper
substitution in all cases.
ABS (10-20) would be converted to
10-20 < 0 ? -10-20 : 10-20
Shivani Varshney/RCET/Programming with C
Preprocessor Directive
Shivani Varshney/RCET/Programming with C
Preprocessor directives are lines included in the code
of our programs that are not program statements but
directives for the preprocessor.
These lines are always preceded by a hash sign (#).
The preprocessor is executed before the actual
compilation of code begins, therefore the
preprocessor digests all these directives before any
code is generated by the statements.
Shivani Varshney/RCET/Programming with C
The preprocessor directives are shown here:
#define #endif #ifdef #line
#elif #error #ifndef #pragma
#else #if #include #undef
Shivani Varshney/RCET/Programming with C
#define
The #define directive defines an identifier and a
character sequence (a set of characters) that will be
substituted for the identifier each time it is
encountered in the source file.
The identifier is referred to as a macro name and the
replacement process as macro replacement.
The general form of the directive is
#define macro-name char-sequence
Shivani Varshney/RCET/Programming with C
There is no semicolon in this statement. There may
be any number of spaces between the identifier and
the character sequence, but once the character
sequence begins, it is terminated only by a newline.
Example:
If we wish to use the word LEFT for the value 1 and the
word RIGHT for the value 0, we could declare these two
#define directives:
#define LEFT 1
#define RIGHT 0
Shivani Varshney/RCET/Programming with C
This causes the compiler to substitute a 1 or a 0 each
time LEFT or RIGHT is encountered in your
source file.
For example, the following prints 0 1 2 on the screen:
printf("%d %d %d", RIGHT, LEFT, LEFT+1);
Shivani Varshney/RCET/Programming with C
#error
The #error directive forces the compiler to stop
compilation. It is used primarily for debugging. The
general form of the #error directive is
#error error-message
The error-message is not between double quotes.
When the #error directive is encountered, the
error message is displayed, possibly along with other
information defined by the compiler.
Shivani Varshney/RCET/Programming with C
#include
The #include directive tells the compiler to read
another source file in addition to the one that
contains the #include directive.
The name of the source file must be enclosed
between double quotes or angle brackets.
Shivani Varshney/RCET/Programming with C
Example,
#include "stdio.h"
#include <stdio.h>
Both cause the compiler to read and compile the
header for the I/O system library functions.
Include files can have #include directives in them.
This is referred to as nested includes.
The number of levels of nesting allowed varies
between compilers.
Shivani Varshney/RCET/Programming with C
Conditional Compilation Directives
There are several directives that allows to selectively
compile portions of your program's source code. This
process is called conditional compilation and is used
widely by commercial software houses that provide
and maintain many customized versions of one
program.
Shivani Varshney/RCET/Programming with C
#if, #else, #elif, and #endif
These directives allow you to conditionally include
portions of code based upon the outcome of a
constant expression.
The general form of #if is
#if constant-expression
statement sequence
#endif
Shivani Varshney/RCET/Programming with C
If the constant expression following #if is true, the code
that is between it and #endif is compiled.
Otherwise, the intervening code is skipped. The #endif
directive marks the end of an #if block.
For example:
{
/* Simple #if example. */ #if MAX>99
#include <stdio.h> printf(''Compiled for array
#define MAX 100 greater than 99.\n");
#endif
int main(void)
return 0;
This program displays the} message on the screen
because MAX is greater than 99.
Shivani Varshney/RCET/Programming with C
The #else directive works much like the else that is
part of the C language:
It establishes an alternative if #if fails. The previous
example can be expanded as shown here:
#if MAX>99
/* Simple #if/#else example. */ printf("Compiled for array greater
#include <stdio.h> than 99.\n");
#define MAX 10 #else
printf("Compiled for small
int main(void)
array.\n");
{ #endif
return 0;
}
Shivani Varshney/RCET/Programming with C
Some pointer concepts
Shivani Varshney/RCET/Programming with C
Pointer I
Shivani Varshney/RCET/Programming with C
Pointer II
Shivani Varshney/RCET/Programming with C
Pointer III
Shivani Varshney/RCET/Programming with C
Pointer IV
Shivani Varshney/RCET/Programming with C
Pointer V
Shivani Varshney/RCET/Programming with C
Pointer VI
Shivani Varshney/RCET/Programming with C
Recursion
Recursive functions
Functions that call themselves
Can only solve a base case
Divide a problem up into
What it can do
What it cannot do
What it cannot do resembles original problem
The function launches a new copy of itself (recursion step) to
solve what it cannot do
Eventually base case gets solved
Gets plugged in, works its way up and solves whole problem
Shivani Varshney/RCET/Programming with C
Recursion
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;
Shivani Varshney/RCET/Programming with C
Example Using Recursion: The Fibonacci Series
Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
Each number is the sum of the previous two
Can be solved recursively:
fib( n ) = fib( n - 1 ) + fib( n – 2 )
Code for the fibaonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}
Shivani Varshney/RCET/Programming with C
5.14 Example Using Recursion: The Fibonacci
Series
Set of recursive calls to function fibonacci
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Shivani Varshney/RCET/Programming with C
1 /* Fig. 5.15: fig05_15.c
2 Recursive fibonacci function */
3 #include <stdio.h>
4
1. Function prototype
5 long fibonacci( long );
6
7 int main() 1.1 Initialize variables
8 {
9 long result, number;
10 2. Input an integer
11 printf( "Enter an integer: " );
12 scanf( "%ld", &number );
2.1 Call function
13 result = fibonacci( number );
14 printf( "Fibonacci( %ld ) = %ld\n", number, result );
fibonacci
15 return 0;
16 } 2.2 Output results.
17
18 /* Recursive definition of function fibonacci */
19 long fibonacci( long n ) 3. Define fibonacci
20 { recursively
21 if ( n == 0 || n == 1 )
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
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2 Program Output
Enter an integer: 4
Fibonacci(4) = 3
Enter an integer: 5
Fibonacci(5) = 5
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
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)
Shivani Varshney/RCET/Programming with C