Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Cps Module 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

MODULE-4

USER DEFINED FUNCTIONS AND RECURSION

4.1 INTRODUCTION TO USER DEFINED FUNCTIONS

What is a Function?
A function is a collection of statements that performs a specific task or job.
Function are very useful to read, write, debug and modify complex program.
Function can also be called as SUB-PROGRAM or PROCEDURE or SUB-
ROUTINE.

4.2 NEED FOR USER-


USER-DEFINED FUNCTIONS

Advantages of Function:
• One reason to use functions is that they break a program up into small,
manageable units.
• Each unit is a module, programmed as a separate function.
example:
Imagine a book that has a thousand pages, but isn’t divided into
chapters or section.
• Another reason to use function is that they simplify programs. If a specific
task is performed several places in a program, a function can be written
once to perform that task and then be executed any time it is needed.

Main Program

Function A Function B Function C

Top-down modular programming using function

4.3 TYPE OF FUCTIONS IN C

There are basically two types of functions those are:


1. Library function or Built-
Built-in function
2. User Defined Function.

Library Function: All the built-functions supported by the C Language are called
as Library Function. These functions are stored in HEADER FILES. Built-in
functions cannot be modified; it can only read and can be used.

Dept. of ISE, Sapthagiri College of Engg. 1


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Example:
printf(), scanf(), sqrt(), strcpy() etc

User Defined Functions: The user defined functions defined by the user
according to its requirement. Instead of relying only on built-in functions.
for example:
if we want to calculate the standard deviation or some mathematical calculations
then we can place them in separate function with proper function name and then
we can call that function multiple times.

4.4 A MULTI-
MULTI-FUNCTION PROGRAM

A function is a self-contained block of code that performs a particular task. Once


a function has been designed and packed, it can be treated as a ‘black box’ that
takes some data form the main program and returns a value.

Any function can call any other function. In fact, it can call itself. A ‘called
function’ can also call another function. A function can be called more than once.
In fact, this is one of the main features of using functions.
main( )
{
---------
function1( );
----------
function2( );
----------
function1( ); call
return -----------
}
call

function1( )
{
-------------
return }

function2( )
{
------------
function3( );
}
call

return function3( )
{
----------
}

Dept. of ISE, Sapthagiri College of Engg. 2


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

4.5 ELEMENTS OF USER DEFINED FUNCTIONS


FUNCTIONS

In order to make use of a user-defined function, we need to establish three


elements that are related to functions
1. Function definition.
2. Function call.
3. Function declaration.

1. FUNCTION DEFINITION or DEFINITION OF FUNCTION

A function definition, also known as function implementation shall include the


following elements;

1. function name;
2. function type;
3. list of parameters;
4. local variable declarations;
5. function statement; and
6. a return statement.
All the six elements are grouped into two parts, namely,
o function header(First three elements);
o function body(Second three elements)

Syntax:

function_type function_name(parameter list)


{
local variable declaration;

Execute statement 1;
Execute statement 2;
………
………
return statement;
}

Function Header: The function header consists of three parts:


 the function type or return type
 the function name
 the formal parameter list.
Note: that a semicolon is not used at the end of the function header.

Name and Type:


 The function type specifies the type of value(like float or double) that the
function is expected to return to the program calling the function.
function If the
return type is not explicitly specified. C will assume that it is an integer
type.

Dept. of ISE, Sapthagiri College of Engg. 3


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

 If the function is not returning anything, then we need to specify the


return type as void.
void Remember, void is one of the fundamental data types
in C.
 the function name is any valid C identifier and therefore must follow the
same rules of formation as other variable names in C.

Formal Parameter List or Argument List:


List:

 The formal parameter list declares the variables that will receive the data
sent by the calling program. They serve as input data to the function to
carry out the specified task.
 These parameters can also be used to send values to the calling programs.
 The parameter list contains declaration of variables separated by commas
and surrounded by parentheses.

Example:

float quadratic(int a, int b, int c)


{

-------------
-------------
}

int sum(int a, int b)


{
------------
------------
}

Note: int sum(int a,b) //illegal structure or syntax

 A function need not always receive values from the calling program. In
such cases, functions have no formal parameters. To indicate that the
parameter list is empty, we use the keyword void between the parentheses
as in

void printline(void)
{
-------------
-------------
}
the function neither receives any input values nor returns back any value.

Dept. of ISE, Sapthagiri College of Engg. 4


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Function body:

The function body contains the declarations and statements necessary for
performing the required task.

The body enclosed in braces, contains three parts, in the order given
below.
1. Local declarations that specified 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.

Note:
 If a function does not return any value, we can omit the return statement.
However, note that its return type should be specified as void.

Example:

float mul(float x, float y)


{
float result ; //local variable
result = x * y; // computes the product
retrun(result); // returns the result
}

void sum (int a, int b)


{
/* no local variables */
printf(“sum = %s”, a + b);
return; /* optional */
}

void display(void)
{
/* no local variables */
printf(“No type, no parameter”);
/* no return statement */
}

Dept. of ISE, Sapthagiri College of Engg. 5


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Return Values and


and Their Types

While it is possible to pass to the called function any number of values, the called
function can only return one value per call, at the most.

the return statement can take one of the following forms:

return;

or

return(expression);

the first, the ‘plain’ return does not return any value; it acts much as the closing
brace of the function. When a return is encountered, the control is immediately
passed back to the calling function.

example:
if(error)
return;

Note:
1. function can have one return statement
int mul(int x, int y)
{
int p;
p = x* y;
return(p);
}
2. A function may have more than one return statements
int xyz(int x )
{
if(x < 0)
return(0);
else
return(1);
}
3. In functions that do computations using doubles, yet return ints, the
returned value will be truncated to an integer.
int product(void)
{
return(2.5 * 3.0);
}

Dept. of ISE, Sapthagiri College of Engg. 6


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

2. FUNCTION CALLS

A function can be called by simply using the function name followed by a list of
ACTUAL PARAMETERS (or Arguments), if any, enclosed in parantheses

Example:

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

int mul(int x, int y)


{
Formal parameter
int p;
p= x*y;
return(p);
}

void main()
{
int a,b,result;
clrscr();
printf("enter the value of a and b\n");
scanf("%d%d",&a,&b);
result=mul(a,b); /* function call */
Actual Parameter
printf("The product of two number is= %d",result);
getch();
}

output:
enter the value of a and b
4
5
The product of two numbe is = 20

NOTE:

1. There are many different ways to call a function.

o mul(10,5);
o mul(a,b);
o mul(10,b);
o mul(a,5);
o mul(a+5, 10)
o mul(10,mul(a,b));
o mul(expression1, expression2);

Dept. of ISE, Sapthagiri College of Engg. 7


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

2. A function which returns a value can be used in expressions like any other
variable.
example:

 printf(“%d\n”,mul(a,b);
 y = mul(p,q)/(p+q);
 if (mul(m,n)>total) printf(“large”);

3. A function cannot be used on the right side of an assignment statement


example
mul(a,b) = 15; //invalid

3. FUNCTION DECLARATION

Like variables, all functions in a C program must be declared, before they are
invoked. A function declaration ( also known as function prototype) consists of
four parts.

 Function type(return type)


 Function name
 Parameter list
 Terminating semicolon

Syntax:

function_type Function_name ( parameter lists);

#include<stdio.h>
int add(int , int ); /* Function Declaration */

void main( )
{

int a=5,b=6,c;

c= add(a,b);
printf(“ The addition of two number= %d”,c);

int add(int x, int y)


{

return (x + y);

Dept. of ISE, Sapthagiri College of Engg. 8


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

4.6 CATEGORY OF FUNCTIONS OR TYPES OF USER


DEFINED FUNCTIONS

The user-define functions are classified into five types, according to parameters
and return value.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and one return values.
4. Functions with no arguments but return a values.
5. Functions that return multiple values.

1. NO ARGUMENTS AND NO RETURN VALUES

The calling function will not send parameters to the called function and called
function will not pass the return value to the calling function.

Example:
Write a program to add two number using function call with no parameters and
no return value.

#include<stdio.h>
void add( ); /* function prototype */

int main( )
{
add();
retrun 0;
}

void add( )
{
int a,b,c; /* local variable */
printf(“Enter the value of a and b”);
scanf(“%d%d”,&a,&b);
c = a + b;
printf(“Sum of two number is = %d”,c);
}

Output:
Enter the value of a and b
2
3
Sum of two number is = 5

Dept. of ISE, Sapthagiri College of Engg. 9


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

2. FUNCTIONS WITH ARGUMENTS AND NO RETURN VALUES.

The calling function will pass parameters to the called function but called
function will not pass the return value to the calling function.

#include<stdio.h>
void add(int , int ); /* function prototype */

int main( )
{
int a=4,b=5;
printf(“The values of a and b: %d %d”,a,b);
add(a,b);
retrun 0;
}

void add(int x, int y )


{
int c;
c = a + b;
printf(“Sum of two number is = %d”,c);
}

3. FUNCTIONS WITH ARGUMENTS AND ONE RETURN VALUES.

The calling function will pass parameters to the called function and called
function also pass the return value to the calling function.
#include<stdio.h>
int add(int , int ); /* function prototype */

int main( )
{
int sum, a=4,b=5;
printf(“The values of a and b: %d %d”,a,b);
sum=add(a,b);
printf(“Sum of two number is = %d”,sum);
retrun 0;
}

int add(int x, int y )


{
int c;
c = a + b;
return c;
}

Dept. of ISE, Sapthagiri College of Engg. 10


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

4. FUNCTIONS WITH NO ARGUMENTS BUT RETURN VALUES.


VALUES.

The calling function will not pass parameter to the called function but called
function will pass the return value to the calling function.

#include<stdio.h>
int add( ); /* function prototype */

int main( )
{
int sum;
sum=add( );
printf(“Sum of two number is = %d”,sum);
retrun 0;
}

int add( )
{
int a=5, b=6;
printf(“ The value of a and b: %d %d “,a,b);
c = a + b;
return c;
}

5. FUNCTIONS THAT RETURN MULTIPLE VALUES(PASS


VALUES(PASS BY
ADDRESS).
ADDRESS).

Up till now, we have illustrated functions that return just one value using a
return statement. That is because, a return statement can return only one value.
Suppose, however, that we want to get more information from a function. We can
achieve this in C using the arguments not only to receive information but also to
send back information to the calling function. The arguments that are used to
“send out” information are called OUTPUT PARAMETERS.

This mechanism of sending back information through arguments is achieved


using what are known as the ADDRESS OPERATOR (&) and INDIRECT
OPERATOR(*).

Example:

#include<stdio.h>

void mathoperation(int ,int , int *, int *);

void main( )

int x=20, y=10, s,d;

Dept. of ISE, Sapthagiri College of Engg. 11


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

mathoperation(x,y,&s,&d);
printf(“s=%d\n d=%d\n”,s,d);

void mathoperation(int a,int b,int *sum,int *diff)


{

*sum = a+b;
*diff = a – b;
}

4.7 PASSING PARAMETERS TO FUNCTION

What are the different ways of passing parameters to the functions?


There are two ways of passing parameters to the functions

1. Pass by value(call by value)


2. Pass by address

Pass by Value: The value of actual parameters is copied into formal parameters.
note: if the values of the formal parameters changes in the called function, the
values of the actual parameter are not changed.

Example:
write a C program to find square of the number using pass by value.
#include<stdio.h>
#include<conio.h>
int square(int);
void main()
{
int n,res;
clrscr();
printf("enter the value of n to find square \n");
scanf("%d",&n);

res=square(n);

printf("the square of the number %d is %d\n",n,res);


getch();
}
int square(int m)
{
int s;
s=m*m;
return s;
}

Dept. of ISE, Sapthagiri College of Engg. 12


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

output:
enter the value of n to find square
4
the square of the number 4 is 16

example2:
#include<stdio.h>
#include<stdio.h>
void mathoperation(int ,int , int , int );

void main( )

int x=20, y=10, s,d;


clrscr();
mathoperation(x,y,s,d);
printf("s=%d\n d=%d\n",s,d);
getch();

void mathoperation(int a,int b,int sum,int diff)


{

sum = a+b;
diff = a*b;
}

output :
s= some garbage value
d=some garbage value

example 2:

Write a program to swap a two element using pass by value


#include<stdio.h>

void exchange(int m, int n)


{ m 5 n 8
int temp;
m=8 n=5
temp = m; Exchange
m=n;
n = temp; No
} Exchange
void main( ) a 5 b 8

Dept. of ISE, Sapthagiri College of Engg. 13


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

int a,b;
a=10, b=20;
exchange(a,b);
printf(“a=%d and b=%d\n”,a,b)

NOTE:

1. the exchange function is swap the two number but it will not return more
than one value by using call by value.

4.8 NESTING OF FUNCTIONS

C permit nesting of functions freely. main can call funtion1, which calls function2,
which call function3, ……… and so on.

Example:

Write a C program calculates the ratio a/(b-c) and print the result using nesting
function.

#include<stdio.h>
#include<conio.h>
float ratio(int x, int y, int z);
int difference(int x , int y);

void main()
{
int a,b,c;
clrscr();
printf("enter the value of a,b and c \n");
scanf("%d%d%d",&a,&b,&c);
printf("The ratio of=%f",ratio(a,b,c));
getch();
}

float ratio(int x, int y, int z)


{
if(difference(y,z))
{
return( x/(y-z));
}
else
{
return(0.0);

Dept. of ISE, Sapthagiri College of Engg. 14


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

}
}
int difference(int p, int q)
{
if(p != q)
return(1);
else
return(0);
}

4.9 RECURSION

When function call itself( inside function body) again and again then it is called as
recursive function.

Example:

main( )
{

printf(“This is an example of recursion \n”);


main( );
}

output:

This is an example of recursion


This is an example of recursion
This is an example of recursion
:
:
:

Execution is terminated abruptly; otherwise the execution will continue


indefinitely.

Dept. of ISE, Sapthagiri College of Engg. 15


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Example 2:

FACTORIAL
Write a C program to find Factorial of a Number using recursion.

#include<stdio.h>
int fact(int num)
{
if(num==0 || num==1)
{
return 1;
}
else
{
return(num * fact(num-1);
}
}
int main()
{
int n,res;
clrscr();
printf("Please Enter any number to find factorial\n");
scanf("%d",&n);
res=fact(n);
printf("\n Factorial of %d = %d\n",n,res);
getch();
return 0;
}

output:

Please Enter any number to find factorial


5
Factorial of 5 = 120

Explanation:

User enter value = 5

fact = num * fact(num-1);

fact = 5 * fact(5-1)
= 5 * fact(4)
= 5 * 4* fact(3)
= 5 * 4 * 3 * fact(2)
= 5 * 4 * 3 * 2 * fact (1)
= 5*4*3*2*1
= 120

Dept. of ISE, Sapthagiri College of Engg. 16


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Write a C program to find factorial of a number using function ( no Recursive


function)

#include<stdio.h>
int fact(int num)
{
int i, f=1;

for(i=1; i<=num; i++)


{
f = f * i;
}

return f;

int main()
{
int n,res;
clrscr();
printf("Please Enter any number to find factorial\n");
scanf("%d",&n);
res=fact(n);
printf("\n Factorial of %d = %d\n",n,res);
getch();
return 0;
}

FIBONACCI SERIES:

Definition: The Fibonacci numbers are a series of numbers such that each
number is the sum of the previous two numbers except the first and second
number.

0 1 1 , 2 , 3 ,5 , 8, 13, …..

base case general case


The Recursive definition to find nth Fibonacci number can be written

0 if n = 0

Fib(n) = 1 if n=1

fib(n-1) + fib (n-2) if n > 2

Dept. of ISE, Sapthagiri College of Engg. 17


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Example:

Write a C program to Print Fibonacci Series using Recursion.

#include<stdio.h>

int Fibonacci(int);

int main()
{
int n, i ;

clrscr();
printf("Please Enter Number to find Fibonacci series\n");
scanf("%d",&n);

printf("Fibonacci series\n");

for ( i = 0 ; i <= n ; i++ )


{
printf("%d\n", Fibonacci(i));
}
getch();
return 0;
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

output:

Please Enter Number to find Fibonacci series


0
1
1
2
3
5

Dept. of ISE, Sapthagiri College of Engg. 18


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Program to print Fibonacci Series of Number using Function in C


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
void fibo(int n);
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
printf("Fibonacci Series\n0\n1\n");
fibo(n);
getch();
}
void fibo(int n)
{
int a=0,b=1,c,i;
for(i=1;i<=n-2;i++)
{
c=a+b;
printf("%d\n",c);
a=b;
b=c;
}
}

4.10 PASSING ARRAYS TO FUNCTIONS

Like the values of simple variables, it is also possible to pass the values of an array
to a function.

Passing single element of an array to function


Passing One Dimensional Arrays:

#include <stdio.h>
void display(int age)
{
printf("%d", age);
}

int main()
{
int ageArray[] = {2, 3, 4};
display(ageArray[2]); //Passing array element ageArray[2]
return 0;
}
output:
4

Dept. of ISE, Sapthagiri College of Engg. 19


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

Passing an entire array to a function

// Program to calculate average by passing an array to a function

#include <stdio.h>
float average(float age[]);

int main()
{
float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}

float average(float age[])


{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}

output:
Average age = 27.08

Passing two-dimensional array to a function

#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);

// passing multi-dimensional array to a function


displayNumbers(num);
return 0;
}

Dept. of ISE, Sapthagiri College of Engg. 20


USER DEFINED FUNCTIONS AND RECURSION MODULE 4 Sudarsanan D

void displayNumbers(int num[2][2])


{
int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}

Output

Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

9. 11 PASSING STRINGS TO FUNCTIONS

Strings can be passed to a function in a similar way as arrays. Learn more about
passing array to a function.

#include <stdio.h>
void displayString(char str[]);

int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}

Dept. of ISE, Sapthagiri College of Engg. 21

You might also like