0% found this document useful (0 votes)
31 views17 pages

CPPS Mod

1. Functions are independent program modules that are designed to carry out a particular task. User-defined functions are written by programmers to serve their own purpose. 2. Modular programming involves organizing a large program into small, independent program segments called modules that are separately callable units. This is a "divide-and-conquer" approach to problem solving. 3. The elements related to functions are the function definition, function call, and function declaration. The function definition includes the function name, return type, parameters, local variables, statements, and return statement.

Uploaded by

dxxxksh
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)
31 views17 pages

CPPS Mod

1. Functions are independent program modules that are designed to carry out a particular task. User-defined functions are written by programmers to serve their own purpose. 2. Modular programming involves organizing a large program into small, independent program segments called modules that are separately callable units. This is a "divide-and-conquer" approach to problem solving. 3. The elements related to functions are the function definition, function call, and function declaration. The function definition includes the function name, return type, parameters, local variables, statements, and return statement.

Uploaded by

dxxxksh
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/ 17

Module 4 C Programming for Problem Solving

MODULE 4:

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

Dept. of CSE, CBIT, KOLAR 1


Module 4 C Programming for Problem Solving

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 ( )
main( ) calls add( ) completes the work
and returns back to
main( )

add( ) completes the main( ) calls


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

Function Black- output


inputs box

Note: As shown in the above diagram, function can accept any number of inputs but can retu
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.

Dept. of CSE, CBIT, KOLAR 2


Module 4 C Programming for Problem Solving

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.

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;

Dept. of CSE, CBIT, KOLAR 3


Module 4 C Programming for Problem Solving

executable statement2;
......
......
return statement;
}
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

Dept. of CSE, CBIT, KOLAR 4


Module 4 C Programming for Problem Solving

Syntax:function_type function_name(parameter_list);

Ex: int sum(int, int);

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.

Dept. of CSE, CBIT, KOLAR 5


Module 4 C Programming for Problem Solving

Figure 3: No data communication between functions


void display(void); 1
int main( ) 2 Parts of user defined function marked in the
{ example given are:

1. function prototype
display( ); 3 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

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, ty[e and order as
shown in Figure 3.

Dept. of CSE, CBIT, KOLAR 6


Module 4 C Programming for Problem Solving

Figure 4: One-way data communication

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

void show(int);
1
int main( ) 2 Description of user defined function marked in the
{ example given is:
int num=5; 1. function prototype of show( ) has an
show(num); 3 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 displays it on
{
4 screen
printf(“%d”, no);
return;
}

Dept. of CSE, CBIT, KOLAR 7


Module 4 C Programming for Problem Solving

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

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); Description of user defined function marked in


1
int main( ) 2 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 value
void SquareMaker(int sq)
passed by ‘num’ and square of that
{
number is calculated and sent back to
return(sq * sq); 4
main
}

Dept. of CSE, CBIT, KOLAR 8


Module 4 C Programming for Problem Solving

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 in


1
2 the example given are:
int main( )
1. function prototype of SquareMaker( )
{ has an integer no parameter but return
int square; type is ‘int’
2. calling function
square=SquareMaker( ); 3
3. No parameter is passed to function
printf(“Square of number is %d”, square); SquareMaker( ) while calling it
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.

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

Dept. of CSE, CBIT, KOLAR 9


Module 4 C Programming for Problem Solving

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 temp*/


Value in a=5 Copied to x 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

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.

Dept. of CSE, CBIT, KOLAR 10


Module 4 C Programming for Problem Solving

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

Address of is Copied to
temp=*x /* copies 5 to temp */
a=say(1002) 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 to
b=say 2002 y
Thus ‘a’ and ‘b’ values got swapped
indirectly!

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”);

Dept. of CSE, CBIT, KOLAR 11


Module 4 C Programming for Problem Solving

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

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 calculated*/
num[5] ={3,4, 8, 9, 10}; printf(“square is=%d ”, sq);
for(i=0; i<5; i++) }
{
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.

Dept. of CSE, CBIT, KOLAR 12


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 avg;
int marks[5], i for(i=0; i<5;i++)
float avg1; {
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]

Dept. of CSE, CBIT, KOLAR


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.

Dept. of CSE, CBIT, KOLAR 14


Module 4 C Programming for Problem Solving

 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

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

Dept. of CSE, CBIT, KOLAR 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) );
}
PREVIOUS YEAR QUESTIONS

1. Explain function call, function definition and function prototype with examples to
each.
2. What are actual parameters and formal parameters? Illustrate with example.
3. What is recursion? WACP to compute the factorial of a given number ‘n’ using
recursion.
4. Explain recursion with example.
5. Define the following:
i. Actual parameter
ii. Formal Parameter
iii. Global variable

Dept. of CSE, CBIT, KOLAR 16


Module 4 C Programming for Problem Solving

iv. Local variable


6. What is a function? Write a function to find the sum of two numbers.
7. Explain the two categories of argument passing techniques, with examples.
8. Write a C function isprime(num) that accepts an integer argument and returns 1
if the argument is a prime or a 0 otherwise. Write a program that invokes this
function to generate prime numbers between the given integers.

Dept. of CSE, CBIT, KOLAR 17

You might also like