0% found this document useful (0 votes)
19 views

Module-3 Functions

Uploaded by

Triveni Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Module-3 Functions

Uploaded by

Triveni Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MODULE 3

USER DEFINED FUNCTIONS AND RECURSION

1. INTRODUCTION
Every C program should consist of one or more functions. Among these functions main(
) function is compulsory. All programs start execution from main( ) function.
Functions are independent program modules that are designed to carry out a particular task. In
functions we have two types:
1. Built-in (Library) functions
2. User defined functions

Built-in functions are C language functions already available with C compliers and can be
used by any programmers. Example: printf( ),scanf( )
User-defined functions are written by programmers to serve their own purpose and are not
readily available.

Advantages of using Functions:


Functions based modular programming is advantageous in many ways:
1. Managing huge programs and software packages is easier by dividing them into
functions/modules—Maintenance is easier
2. Error detection is easier—Debugging is easier
3. Functions once written can be re-used in any other applications – Reusability is
enhanced
4. We can protect our data from illegal users—Data protection becomes easier

Figure 1: Top-down modular programming using functions

1
Following block diagram explains how functions are useful:Instead of writing entire program
(to add and subtract) within main( ) function we can write independent modules add( ) and
subtract( ) as shown:

main() Subtract ( )
) completes the work
main( ) calls add( )
and returns back to
main( )

add( ) completes the main( ) calls


work and returns subtract( )
add( ) back to main( ) subtract( )

Function
output
inputs Black- box

Note: As shown in the above diagram, function can accept any number of inputs but one
value as output.

2. MODULAR PROGRAMMING

 Modular programming is defined as organizing a large program into small,


independent program segments called modules that are separately named and individually
callable program units.
 It is basically a “divide-and-conquer” approach to problem solving.
 The characteristics of modular programming are:
1. Each module should do only one thing.
2. Communication between modules is allowed only by calling module.
3. No communication can take place directly between modules that do not have calling-
called relationship.
4. All modules are designed as single-entry, single-exit systems using control structures.
5. A module can be called by one and only higher module.

2
3. ELEMENTS OF USER-DEFINED FUNCTIONS
There are three elements that are related to functions:
i. Function definition
ii. Function call
iii. Function declaration/Function prototype

i. Function definition: It is an independent program module that is specially written to


implement the requirements of the function.
ii. Function call: To function should be invoked at a required place in the program
which is called as Function call. The program that calls the function is referred as calling
program or calling function.
iii. Function declaration: The calling program should declare any function that is to be
used later in the program which is called as function declaration.

DEFINITION OF FUNCTIONS

A function definition, also known as function implementation will include:


i. Function name
ii. Function type/ Return type
iii. List of parameters/ Arguments
iv. Local variable declaration
v. Function statements
vi. A return statement

All the above six elements are grouped into two parts. Namely:
 Function header (First three elements)
 Function body (Second three elements)

Syntax:
function_type function_name(parameter list)
{
local variable declaration; executable
statement1;
executable statement2;
......
......
return statement;
}

3
The first line function_type function_name(parameter list) is known as the function
header and the statements within opening and closing braces is known as the function body.

i. Function Header: It consists of three parts: Function type, function name and formal
parameter list. The semicolon is not present at the end of header.

Function type:
 The function type specifies the type of value that the function is expected to return to
the program calling the function.
 If the return type is not specifies, then it is assumed as int.
 If function is not returning anything, then it is void.

Function name: The function name is any valid C identifier and must follow same rules as
of other variable.
Formal Parameter List:The parameter list declares the variables that will receive the data
sent by the calling program which serves as input and known as Formal Parameter List.

ii. Function Body: The function body contains the declarations and statements necessary
for performing the required task. The body is enclosed in braces, contains three parts:
1. Local declarations that specify the variables needed by the function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.

FUNCTION DECLARATION

A function declaration consists of four parts:


 Function type (return type)
 Function name
 Parameter List
 Terminating semicolon

Syntax:function_type function_name(parameter_list);

Ex: int sum(int, int);

4
4. CATEGORIES OF FUNCTIONS

User defined
functions

Functions return
nothing Functions with return
value
(void functions)

void functions Functions with


without parameters and
parameters return values

Functions without
void functions with parameters and
parameters with return values

Figure 2: Categories of Functions


1. Void Functions without parameters – No arguments and no return values

 When a function has no arguments, it does not receive any data from the calling
function.
 Similarly, when it does not return a value, the calling function does not receive any
data from the called function.

Figure 3: No data communication between functions

5
void display(void);
int main( ) 1
{ 2 Parts of user defined function marked in the
example given are:
display( ); 3 1. function prototype
2. calling function
3. called function/function call
} 4. function definition
4a
a. function header
void display(void ) i. return type
{ ii. function name
printf(“Welcome to the C World”); iii. parameters if any
return; b. function body
}

4b

6
2. Void Functions with parameters – Arguments but no return values

 The calling function accepts the input, checks its validity and pass it on to the called
function.
 The called function does not return any values back to calling function.
 The actual and formal arguments should match in number, type and order as shown in
Figure 3.

Figure 4: One-way data communication

Figure 5: Arguments matching between the function call and the called function

7
void show(int);
int main( ) 2 1
Description of user defined function marked in
{
the example given is:
int num=5;
show(num); 3 1. function prototype of show( ) has
an integer parameter ‘int’
2. calling function main ( )
}/* end of main */
3. actual parameter ‘num’ is
passed to function show( )
void show(int no) 4. formal parameter ‘no’contains
{ value 5 copied from ‘num’ and
printf(“%d”, no); 4 displays it on screen
return;
}

In this example a photocopy of value stored in ‘num’ (i.e. 5) is made in ‘no’ and finally
displayed on screen. Next let us discuss functions with parameters and return values.

8
3. Functions with parameters and return values – Arguments with return
values

 The calling function sends the data to called function and also accepts the return
values from called function.
 Actual Parameters: When a function is called, the values that are passed in the call
are called actual parameters.
 Formal Parameters:The values which are received by the function, and are
assigned to formal parameters.

Figure 6: Two-way data communication between functions

int SquareMaker (int); 1 Description of user defined function marked


int main( ) 2 in the example given is:
{
1. function prototype of SquareMaker(
int num, square; ) has an integer parameter ‘int’ and
printf(“Enter the number”); return type ‘int’
scanf(“%d”, &num); 2. calling function
square=SquareMaker(num); 3 3. actual parameter ‘num’ is passed to
printf(“Square of number is %d”, square); function SquareMaker( ) and the
evaluated value is stored in variable
}
square
4. formal parameter ‘sq’ contains
void SquareMaker(int sq) value passed by ‘num’ and square
{ of that number is calculated and
return(sq * sq); 4 sent back to main
}

9
4. Functions without parameters and with return values – No arguments but
returns values

 The calling function does not send any data to called function and but, accepts the
return values from called function.
 Global Variables: These are declared outside any function, and they can be
accessed on any function in the program.
 Local Variables: These are declared inside a function, and can be used only
inside that function.

int SquareMaker ( ); Description of user defined function marked


1
2 in the example given are:
int main( )
1. function prototype of SquareMaker( )
{ has an integer no parameter but
int square; return type is ‘int’
2. calling function
square=SquareMaker( ); 3 3. No parameter is passed to function
SquareMaker( ) while calling it
printf(“Square of number is %d”, square);
4. SquareMaker( ) calculates square of
} ‘sq’ and returns that value back to
main( )
void SquareMaker( )
{
int sq;
printf(“Enter the number”);
scanf(“%d”, &num);
return(sq * sq); 4

Note: Function call can be an expression like: “square=SquareMaker( )” only in functions with
return values. Void function call cannot be an expression.

10
5. Inter-Function Communication
Two functions can communicate with each other by two methods:

1. By Passing parameters as values (Pass by value)


2. By passing parameters as address (Pass by address)

1. By Passing parameters as values (Pass by value):

In pass-by-value the calling function sends the copy of parameters (Actual


Parameters) to the called function (Formal Parameters).

 The change does not affect the actual value.

void main()
void swap( int x, int y )
{
{
int a=5, b=10;
int temp;
swap(a, b);
temp=x;
printf(“%d %d”, a,b)
x=y;
}
y=temp;

temp=x /* copies 5 to

Value in a=5 Copied to x temp*/ x=y /*copies 10 to


x*/ y=temp /* copies 5 to y
*/
Value in b=10 Copied to y
Thus x and y values got swapped, but problem is a
and b values remain unchanged!
So pass by value method fails here!

Alternative is pass by address/reference

11
2. By Passing parameters as address (Pass by address)

In pass-by-referencethe calling function sends the address of parameters (Actual


Parameters) to the called function (Formal Parameters).

 The change affects the actual value.

void main() void swap( int *x, int *y )


{ {
int a=5, b=10; int temp;

swap(&a, &b); temp=*x;

printf(“%d %d”, a,b) *x=*y;


} *y=temp;

temp=*x /* copies 5 to temp */


Address of is Copied
a=say(1002) to x *x=*y /*copies 10 to *x (i.e. to a) */
*y=temp /* copies 5 to y (i.e. to b) */
Address of is Copied
b=say 2002 to y

12
6. NESTING OF FUNCTIONS
A function within a function is called as nesting of functions.

float checkno(float );
float div(float,float);
main( )
{
float a,b,res;
printf(“enter two numbers\n”);
scanf(“%f%f”),&a,&b);
div(a,b);
}
float div(float a, float b);
{
if(checkno(b))
printf(“the result is %f”, a/b);
else
printf(“division not possible”);

}
float checkno(float b);
{
if(b!=0)
return 0;
else
return 1;
}

13
7. PASSING ARRAYS TO FUNCTIONS
In large programs that use functions we can pass Arrays as parameters. Two ways of passing
arrays to functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter

Let us take an example program that uses a function square( ) to calculate square of numbers
stored in an array. In this program each array element is passed one by one.

Example-1 Example-1 cont’d:


int square(int); void square(int no )
void main( ) {
{ int sq;
int num[5], i; sq=no*no; /*square is
num[5] ={3,4, 8, 9, 10}; calculated*/
for(i=0; i<5; i++) printf(“square is=%d ”, sq);
{ }
square(num[i]);
}
}
} Output:
Square is=9 16 64 81 100

This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter no.

14
Module 4 C Programming for Problem Solving

3 4 8 9 10
0 1 2 3 4 num[3]=9 no

num[1]=4 copied  no

num[0]=3 copied to no
num[2]=8 no

Next program illustrates how to pass an entire array to a function average( ) and calculate
average marks. First sum of all the elements of array marks (i.e.35+65+75+95+85) is
calculated and average is stored in a variable avg. value in avg variable is returned to main( )
and stored in avg1

Example-2: Example-2 cont’d:


float average(int score[ ] )
float average(int score[]); {
void main( ) int i ,
{ sum=0; float
int marks[5], i avg;
float avg1; for(i=0; i<5;i++)
marks[5] ={35,65, 75, 95, {
85}; sum=sum+score[i];
avg1=average(marks); }
printf(“average=%f”, avg1) avg=sum/5;
} return (avg);
}

Output:
average=71.000000

In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
marks[0]=35 copied to scores[0]

marks[1]=65 copied to scores[1]

marks[2]=75 copied to scores[2]

marks[3]=95 copied to scores[3]

marks[4]=85 copied to scores[4] 13

using these values average is calculated:


Module 4 C Programming for Problem Solving

8. PASSING STRINGS TO FUNCTIONS


The strings are treated as character arrays in C and therefore the rules for passing
strings to functions are very similar to those for passing arrays to functions.
Basic rules are:
1. The string to be passed must be declared as a formal argument of the function
when it is defined.
EX: void display(char item_name[])
{
......
......
}
2. The function prototype must show that the argument is a string. Ex:
void display(char str[])
3. A call to the function must have a string array name without subscripts as its
actual argument.
Ex: display(names);
Where names is a properly declared string in the calling function.

9. RECURSION

Programmers use two approaches to writing repetitive algorithms:


 One approach is to use loops
 The other uses recursion

 Recursion is the repetitive process in which a function calls itself.


 All recursive functions have two elements each call either solves one part of the
problem or it reduces the size of the problem.

 The statement that solves the problem is known as base case.


 The rest of the function is known as general case.

Ex: Recursive definition of factorial


Fact(n)= 1 if n=0 base case
n*fact(n-1) if n>0 general case

14
Module 4 C Programming for Problem Solving

Limitations of Recursion
 Recursive solutions may involve extensive overhead because they use function calls.
 Each time you make a call, you use up some of your memory allocation. If
recursion is deep, then you may run out of memory.

PROGRAMS
1. Write a C program to find a factorial of number using recursion.
#include<stdio.h> int
fact(int);
void main( )
{
int n,res;
printf(“enter the number to find its factorial\n”); scanf(“%d”,&n);
res=fact(n);
printf(“factorial of %d=%d”,n,res); getch();
}

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

15
Module 4 C Programming for Problem Solving

2. Program to generate Fibonacci series using recursion


#include<stdio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
printf(" enter the number of terms\n");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

You might also like