Cps Module 4
Cps Module 4
Cps Module 4
MODULE-4
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.
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
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.
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
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( )
{
----------
}
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:
Execute statement 1;
Execute statement 2;
………
………
return statement;
}
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:
-------------
-------------
}
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.
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:
void display(void)
{
/* no local variables */
printf(“No type, no parameter”);
/* no return statement */
}
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.
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);
}
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>
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:
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);
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. 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.
Syntax:
#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);
return (x + y);
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.
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
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;
}
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;
}
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;
}
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.
Example:
#include<stdio.h>
void main( )
mathoperation(x,y,&s,&d);
printf(“s=%d\n d=%d\n”,s,d);
*sum = a+b;
*diff = a – b;
}
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);
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( )
sum = a+b;
diff = a*b;
}
output :
s= some garbage value
d=some garbage value
example 2:
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.
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();
}
}
}
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( )
{
output:
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:
Explanation:
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
#include<stdio.h>
int fact(int num)
{
int i, f=1;
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, …..
0 if n = 0
Fib(n) = 1 if n=1
Example:
#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");
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
output:
Like the values of simple variables, it is also possible to pass the values of an array
to a function.
#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
#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;
}
output:
Average age = 27.08
#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]);
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
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);
}