SlideShare a Scribd company logo
12/12/2020 1
Function
12/12/2020 2
Introduction
C function can be classified into two categories, namely, library functions and user – defined functions.
main is an example of user – defined functions. printf and scanf belong to the category of library functions. We have
also used other library functions such as sqrt, cos, strcat, etc.
The main distinction between these two categories is that library functions are not required to be written by
us whereas a user – defined function has to be developed by the user at the time of writing a program.
Some Characteristic of modular programming are:
1. Each module should do only one thing.
2. Communication between modules is allowed only by a calling module.
3. A module can be called by one and only one higher module
4. No communication can take place directly between modules that do not have calling – called relationship
5. All modules are designed as single – entry, single – exit systems using control structures
12/12/2020 3
1. Every program must have a main function to indicate where the program has to begin its
execution. While it is possible to code any program utilizing only main function. It leads to a
number of problems.
2. The program may become too large and complex and as a result the task of debugging,
testing, and maintaining becomes difficult.
3. If a program is divided into functional parts, then each part may be independently coded and
later combined into a single unit. These subprograms called ‘functions’ are much easier to
understand, debug, and test.
4. The length of a source program can be reduced by using functions at appropriate places. This
factor is particularly critical with microcomputers where memory space is limited.
5. It is easy to locate and isolate a faulty function for further investigations.
6. A function may be used by many other programs.
Need for User – Defined Functions
DEFINITION
A function is a named, independent section of C code that
performs a specific task and optionally returns a value to the
calling program.
• A function is named
• A function is independent.
• A function performs a specific task.
• A function can return a value to the calling program.
12/12/2020 4
Parts of a Function
• FUNCTION DECLARATION
• FUNCTION DEFINITION
• FUNCTION INVOCATION (FUNCTION CALL)
12/12/2020 5
FUNCTION DEFINITION SYNTAX
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 Statements
6. A Return statement
All the six elements are grouped into two parts
namely,
1. Function header (First three Elements)
2. Function Body (Second three Elements)
function_type function_name(parameter_list)
{
local variable declaration;
executable statement_1;
executable statement_2;
---------------------------------
---------------------------------
return statement;
}
Example:
float mul ( float x, float y)
{
float result;
result = x * y;
return (result);
}
12/12/2020 6
FUNCTION PROTYPING OR FUNCTION DECLARATION
• A function prototype is a very important feature of modern
C programming
• It must be added to a C program just before the main
function, if we call that function before defining it
• It tells the compiler what type of value the function returns,
numbers and types of parameters, and order in which these
parameters are expected.
• There is no need for a prototype if the function is called
after its definition
12/12/2020 7
FUNCTION DECLARATION SYNTAX
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.
1. Function type (return type)
2. Function name
3. Parameter list
4. Terminating semicolon
The general format is
Function_type function_name(parameter_list);
Example:
float mul (float x, float y);
12/12/2020 8
Function Prototype
12/12/2020 9
Function Definition
A simple format of a C function definition is as
follows:
return-value-type function-name(parameters)
{
Declarations;
Statements;
Return (expression);
}
S. No. Function prototype Function definition
1. It declares the function. It defines the function
2. It ends with a semicolon. It doesn’t end with a semicolon.
3. Declaration need not include parameters. Definition should include names for the
parameters.
12/12/2020 10
Difference Between Function Prototyping and Function Definition
WORKING PRINCIPLES
12/12/2020 11
Function Terminologies
Local and global variables
• Local: a variable defined inside a function
• Global: a variable defined outside of functions
S. No. Local Variables Global Variables
1. These are declared within the body of the
function.
These are declared outside the function.
2. These variables can be referred only within
the function in which it is declared.
The values of the variables disappear
once the function finishes its execution.
These variable can be referred from any part of
the program value of variables disappear
only after the entire execution or the
program.
12/12/2020 12
Formal and Actual Parameters
• In C, there are two types of parameters
• Formal parameters appear in the prototype and definition, and are
representative of the data types the function expects to receive
• Actual parameters appear only in a function call and are the actual data
passed
12/12/2020 13
Example
#include <stdio.h>
void MyFun( int ); Formal Parameter
int main( void )
{
int x=3;
printf( “x has a value of %d”, x);
MyFun( x ); Actual Parameter
printf( “x has a value of %d”, x);
return 0; Parameter Passing
}
void MyFun( int x ) Formal Parameter
{
printf( “x has a value of %d”, x);
x = 77;
printf( “x has a value of %d”, x);
}
12/12/2020 14
Function prototype and
definition
#include <stdio.h>
int mod(int , int); /* Function Prototype */
void main()
{
printf("The mod is: %d ", mod(4,5));
}
/* Function Definition */
int mod(int x, int y)
{
return x % y;
}
12/12/2020 15
CATEGORIES OF FUNCTIONS
Category 1: Functions with no arguments and no return values.
Category 2: Functions with arguments and no return values.
Category 3: Functions with arguments and one return value.
Category 4: Functions with no arguments but return a value.
Category 5: Functions that return multiple values.
12/12/2020 16
Function with No return type
and No arguments
void main()
{
…….
…….
…….
func1();
…….
}
12/12/2020 17
void func1()
{
…….
…….
…….
…….
}
#include<stdio.h>
void add();
void main()
{
add();
}
void add()
{
int a,b,c;
printf(“enter any two numbers”)
scanf(“%d%d”,&a,&b);
c= a+b;
printf(“the addition of %d and %d is %d”,a,b,c);
}
12/12/2020 18
Function with No return type
and with arguments
Void main()
{
…….
…….
…….
func1(x,y);
…….
}
12/12/2020 19
func1(a,b)
{
…….
…….
…….
…….
}
12/12/2020 20
#include<stdio.h>
void add(int,int);
void main()
{
int x,y,c;
printf(“enter any two numbers”)
scanf(“%d%d”,&x,&y);
add(x,y);
}
void add(int a,int b)
{
int c;
c= a+b;
printf(“the addition of %d and %d is %d”,a,b,c);
}
Function with return type
and with arguments
void main()
{
…….
…….
…….
int func1(x,y);
…….
}
12/12/2020 21
int
func1(a,b)
{
…….
…….
…….
…….
}
#include<stdio.h>
int add(int,int);
Void main()
{
int x,y,c;
printf(“enter any two numbers”)
scanf(“%d%d”,&x,&y);
c = add(x,y);
printf(“The Result = %d ”,c);
}
int add(int a ,int b)
{
int c;
c= a+b;
return (c);
}
12/12/2020 22
Function with return type
and No arguments
void main()
{
…….
…….
…….
int func1();
…….
}
12/12/2020 23
int func1()
{
…….
…….
…….
…….
}
#include<stdio.h>
int add();
Void main()
{
int c;
c = add();
printf(“The Result = %d ”,c);
}
int add()
{
int a,b,c;
printf(“enter any two numbers”)
scanf(“%d%d”,&a,&b);
c= a+b;
return (c);
}
12/12/2020 24
Functions that return multiple values
#include <stdio.h>
void interchange (int *a , int *b)
void main()
{
int i=5,j=10;
printf(“Before : I and J value is %d and %d”,I,j);
interchange(&i,&j);
printf(“After : I and J value is %d and %d”,I,j);
}
void interchange (int *a, int *b)
{
int t;
t=*a
*a=*b
*b=t
} 12/12/2020 25
O/p: Before : I and J value is 5 and 10
After : I and J value is 10 and 5
Function without a prototype
#include <stdio.h>
int sum(int x, int y)
{
return x+y;
}
void main()
{
printf("The sum is: %d ", sum(4,5));
}
12/12/2020 26
Parameter Passing Methods
• In C there are two ways of passing parameters to a function
Call by Value
Call by Reference
12/12/2020 27
Call by value
Copy of data passed to function
Changes to copy do not change original
Prevent unwanted side effects
This Method copies the value of actual parameters(calling program) into
the formal parameters(called program) of the functions.
Here the changes of the formal parameters cannot affect the actual
parameters. Because only the copy of actual arguments were passed.
A function can return only one value per call.
12/12/2020 28
Example
#include <stdio.h>
int cube (int)
void main()
{
int n=5;
printf(“Cube of %d is %d”,n,cube(n));
}
int cube (int x);
{
x=x*x*x;
return x;
}
O/p: Cube of 5 is 125 12/12/2020 29
Call by reference
Function can directly access data
Changes affect original
It is another way of passing parameter to the functions here the
address of arguments are copied into the parameters inside the
functions.
The address is used to access the actual arguments used in the
call.
By using this we can make a function to return more the one
value(indirectly).
12/12/2020 30
Example
#include <stdio.h>
void interchange (int *a , int *b)
void main()
{
int i=5,j=10;
printf(“Before : I and J value is %d and %d”,I,j);
interchange(&i,&j);
printf(“After : I and J value is %d and %d”,I,j);
}
void interchange (int *a, int *b)
{
int t;
t=*a
*a=*b
*b=t
}
12/12/2020 31
O/p: Before : I and J value is 5 and 10
After : I and J value is 10 and 5
Call by value
Vs
Call by reference
• Call by value
Copy of data passed to function
Changes to copy do not change original
Prevent unwanted side effects
• Call by reference
Function can directly access data
Changes affect original
12/12/2020 32
#include <stdio.h>
void swap(int, int);
void main()
{
int num1, num2;
num1 = 10; num2 = 20;
swap ( num1, num2 );
printf("%d %dn", num1, num2);
}
void swap(int val1, int val2)
{
int temp;
temp = val1;
val1 = val2;
val1 = temp;
}
12/12/2020 33
Swap two integers using call by value(cont.)
• In the above example, we passed parameters by value, a copy is made of the variable and thus
any change made to the parameters val1 and val2 will not be passed back to the main function
•The main function will not know anything about
the swapping of val1 and val2
Therefore, the output of the above program will be
….?
• Normally if we wished to pass back a value we
would use return or we would pass the parameters
by reference
12/12/2020 34
Nested Functions
In C , it provides a facility to write one function with in
another function.This is called nesting of functions
12/12/2020 35
Main()
{
---------
func1();
---------
---------
}
func1()
{
---------
func2();
---------
---------
}
func2()
{
---------
---------
---------
---------
}
Recursion
Recursion
Recursion is a process of calling the same function itself
again and again until same condition is satisfied.
This is used for repetitive computation in which each action
is satisfied in terms of a previous result
•A function can call itself
•Directly
•Indirectly
12/12/2020 37
Function1()
{
-----
Function1();
-----
}
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 between performance (iteration) and good software
engineering (recursion)
12/12/2020 38
Sl.No. Iteration Recursion
1. Iteration explicitly user a repetition
structure.
Recursion achieves repetition throught
repeated function calls.
2. Iteration terminates when the loop
continuation condition fails.
Recursion terminates when a base case
is
reached.
3. Iteration keeps modifying the counter
until the loop continuation condition
fails.
Recursion keeps producing simple
versions
of the original problem until the base
case is
reached.
4. An infinite loop occurs when the loop
step
continuation test never becomes false.
An infinite loop occurs if the recursion
doses
not reduce the problem each time in a
manner that converges the base case.
5. Iteration normally occurs within a loop
so
extra memory assignment is omitted.
Recursion causes another copy of the
function & hence a considerable memory
space is occupied.
6. It reduces the processor operating It increases the processor operating
12/12/2020 39
Difference Between Iteration and Recursion
Example: fibonacci.c
function Fibonacci ( n )
{
if ( n is less than or equal to 1 ) then
return n
else
return Fibonacci ( n - 2 ) + Fibonacci ( n - 1 )
}
12/12/2020 40
/* Compute the n-th Fibonacci number,
when=0,1,2,... */
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
Example: Computation of fib(4)
12/12/2020 41
+fib(2) fib(3)
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
4
4
4 4
Example: Computation of fib(4)
12/12/2020 42
fib(2) fib(3)+
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
2 2
+fib(0) fib(1)
Example: Computation of fib(4)
12/12/2020 43
fib(2) fib(3)+
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
0
0
+fib(0) fib(1)
0
Example: Computation of fib(4)
12/12/2020 44
fib(2) fib(3)+
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
0
0
+0 fib(1)
0
Example: Computation of fib(4)
12/12/2020 45
fib(2) fib(3)+
fib(4)
+ fib(1)0
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
220
Example: Computation of fib(4)
12/12/2020 46
fib(2) fib(3)+
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
1
1
+ fib(1)0
1
Example: Computation of fib(4)
12/12/2020 47
fib(2) fib(3)+
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
1
1
+ 10
1
Example: Computation of fib(4)
12/12/2020 48
fib(2) fib(3)+
fib(4)
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
0 21
Example: Computation of fib(4)
12/12/2020 49
1 fib(3)+
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
0
+0 1
21
Example: Computation of fib(4)
12/12/2020 50
+ fib(3)
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
4
4
4 4
1
+0 1
1
Example: Computation of fib(4)
12/12/2020 51
+ fib(3)
fib(4)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
3
3
3 3
1
+0 1 +fib(1) fib(2)
Example: Computation of fib(4)
12/12/2020 52
+ fib(3)
fib(4)
1
+0 1 +fib(1) fib(2)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
1
1
1
Example: Computation of fib(4)
12/12/2020 53
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
1
1
1
Example: Computation of fib(4)
12/12/2020 54
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
3
3
3 31
Example: Computation of fib(4)
12/12/2020 55
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
2 2
+fib(0) fib(1)
Example: Computation of fib(4)
12/12/2020 56
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
+fib(0) fib(1)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
0
0
0
Example: Computation of fib(4)
12/12/2020 57
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
+0 fib(1)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
0
0
0
Example: Computation of fib(4)
12/12/2020 58
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
+0 fib(1)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
2 20
Example: Computation of fib(4)
12/12/2020 59
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
+0 fib(1)
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
1
1
1
Example: Computation of fib(4)
12/12/2020 60
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
1
1
1
Example: Computation of fib(4)
12/12/2020 61
+ fib(3)
fib(4)
1
+0 1 +1 fib(2)
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
2 20 1
Example: Computation of fib(4)
12/12/2020 62
+ fib(3)
fib(4)
1
+0 1 +1 1
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
2
2
2 20 1
Example: Computation of fib(4)
12/12/2020 63
+ fib(3)
fib(4)
1
+0 1 +1 1
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
3
3
3 31 1
Example: Computation of fib(4)
12/12/2020 64
+ 2
fib(4)
1
+0 1 +1 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
3
3
3 31 1
+0 1
Example: Computation of fib(4)
12/12/2020 65
+ 2
fib(4)
1
+0 1 +1 1
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
4
4
4 41 2
Example: Computation of fib(4)
12/12/2020 66
+ 2
3
1
+0 1 +1 1
+0 1
long fib ( int n )
{
if ( n <= 1 )
return n ;
else
return fib( n - 2 ) + fib( n - 1 );
}
4
4
4 41 2
Example: Computation of fib(4)
12/12/2020 67
+ 2
3
1
+0 1 +1 1
+0 1
Thus, fib(4) returns the value 3
Example: fibonacci.c
12/12/2020 68
int main(void)
{
int number;
printf("Enter number: ");
scanf("%d", &number);
printf("Fibonacci(%d) = %ldn",
number, fib(number));
return 0;
}
Sample main() for testing the fib() function:
Scope
Where can you use a variable which is declared in a function?
• In that function only
• Not in a calling function
• Not in a called function
12/12/2020 69
Scope: Local Variables
• Formal parameters: only accessible whilst a function is executing
• Variables declared in a function body: only accessible whilst the function is executing
• In fact, this is true of every block in a program
12/12/2020 70
Exercise
• Write a program to find the factorial using a functions.
• Write a program to find the value of x
n. For any given values of x and n .
12/12/2020 71
Passing arrays to
Functions
Arrays to the function in One dimensional
• An entire array can be transferred to a function as a parameter.
• Actual parameter : the array name is enough without subscripts to transfer an array.
• Formal parameter : must be declared as an array to receive the values from main
program.
syntax :
12/12/2020 73
void func(int,int[])
main() void func(int x, int arr[10])
{ {
int a[10],i; …………
func(i,a); …………
} }
12/12/2020 74
Three Rules of Pass an Array to a Function
1. The function must be called by passing only the name of the array.
2. In the function definition, the formal parameter must be an array type; the
size of the array does not need to be specified.
3. The function prototype must show that the argument is an array.
Sample program
#include<stdio.h>
#inlcude<conio.h>
void add(int[])
void main()
{
int i,arr[10];
printf(“Enter 10 elements of the
array”);
for(i = 0;i<10;i++)
scanf(‘%d”,&arr[i]);
add(arr);
}
12/12/2020 75
void add(int a[])
{
int i,sum = 0;
for(i = 0;i<10;i++)
sum = sum+a[i];
printf(“ the value of sum is %d”,
sum);
}
Changing an Array in a Function
#include <stdio.h>
void fun ( int [ ] )
int main(void)
{
int array[ ] = { 1 , 2 , 3 , 4 , 5 };
fun ( array );
printf ( “%d” , array [ 3 ] ); Will print 20
return 0;
}
void fun ( int x[ ] )
{
x[3] = 20;
return;
}
12/12/2020 76
Largest of Given Numbers
12/12/2020 77
#include<stdio.h>
void main()
{
float largest(float a[ ], int n);
float value [4] = {2.5,-4.75,1.2,3.67};
printf("%fn",largest(value,4);
}
float largest(float a[ ], int n)
{
int i;
float max;
max = a[0];
for(i=1; i<n; i++)
if(max < a[i])
max = a[i];
return(max);
}
Sorting of Given Numbers
12/12/2020 78
#include<stdio.h>
void main()
{
int i;
int mark[5] = {40,90,73,81,35};
printf("Marks before sortingn");
for(i = 0;i<5;i++)
printf("%d",marks[i]);
printf("nn");
sort(5,marks);
printf("Marks after sortingn");
for(i = 0;i<5;i++)
printf("%4d",mark[i]);
printf("n");
}
Sorting of Given Numbers Conti….
12/12/2020 79
void sort(int m,int x[])
{
int i,j,t;
for(i=0;i<m-1;i++)
for(j=i+1;j<m;j++)
if (x[i] > x[j])
{
t = x[i];
x[i] = x[j];
x[j] = t;
}
}
Arrays to the function inTwo dimensional
12/12/2020 80
Like simple arrays, we can also pass multidimensional array to functions.
The approach is similar to the one we did with one – dimensional arrays.
The rules are simple.
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array has two
dimensions by including two sets of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.
Calculates the average of the values in a two – dimensional matrix
12/12/2020 81
#include<stdio.h>
void main()
{
int M = 3, N = 2;
double average (int [] [N],int,int);
double mean;
int matrix [M][N] = {{1,2},{3,4},{5,6}};
mean = average(matrix, M, N);
printf("The Mean of the Two Dimensional Array is: %f",mean);
}
double average(int x [ ] [N],int M,int N)
{
int i,j;
double sum = 0.0;
for(i=0;i<m;i++)
for(j=1;j<N;j++)
sum = sum + x[i][j];
return (sum / (M * N);
}
Passing Strings to Functions
12/12/2020 82
The Strings are treated as character arrays in C, 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.
Example:
void display(char item_name[])
{
----------------
----------------
}
2. The function prototype must show that the argument is a string. For the above function
definition, the prototype can be written as
void display(char str[ ])
3. A call to the function must have a string array name without subscripts as its actual arguments.
Example:
display(names);
where names is a properly declared string array in the calling function.

More Related Content

PPTX
Control Structures in C
PPTX
User defined functions
PPTX
Recursive Function
PPTX
Functions in C
PPT
Ch4 functions
PDF
Lecture20 user definedfunctions.ppt
PPT
user defined function
Control Structures in C
User defined functions
Recursive Function
Functions in C
Ch4 functions
Lecture20 user definedfunctions.ppt
user defined function

What's hot (18)

PPTX
Functions in C
DOC
Basic construction of c
PPTX
Function & Recursion
DOC
c.p function
DOCX
Basic structure of c programming
PPT
DAC training-batch -2020(PLSQL)
PDF
Pointers and call by value, reference, address in C
PDF
Function in C
PDF
Programming Fundamentals Functions in C and types
PDF
C# programs
PPT
Recursion in c
DOC
Functions
PPT
Functions in c
PPTX
Ch9 Functions
PPTX
Ch10 Program Organization
DOC
Storage classess of C progamming
PDF
Data Structure with C
PDF
Chapter 13.1.6
Functions in C
Basic construction of c
Function & Recursion
c.p function
Basic structure of c programming
DAC training-batch -2020(PLSQL)
Pointers and call by value, reference, address in C
Function in C
Programming Fundamentals Functions in C and types
C# programs
Recursion in c
Functions
Functions in c
Ch9 Functions
Ch10 Program Organization
Storage classess of C progamming
Data Structure with C
Chapter 13.1.6
Ad

Similar to Functions (20)

PPTX
L22- L23-Modular programmingpsucmit.pptx
PDF
PSPC-UNIT-4.pdf
PPTX
User Defined Functionscccccccccccccccccccccccccc.pptx
PDF
Functions-Computer programming
PPTX
C concepts and programming examples for beginners
PPT
U19CS101 - PPS Unit 4 PPT (1).ppt
PPTX
Lecture 1_Functions in C.pptx
PPTX
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
PDF
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
PDF
cp Module4(1)
PPTX
Presentation on Function in C Programming
PDF
Functions part1
PDF
Fnctions part2
PPTX
Chapter One Function.pptx
PPTX
Lecture_5_-_Functions_in_C_Detailed.pptx
PPTX
Unit-III.pptx
PPT
Lecture11 abap on line
PPTX
Function C programming
PPTX
functIONS PROGRAMMING CIII II DJDJKASDJKJASD.pptx
PPTX
C functions by ranjan call by value and reference.pptx
L22- L23-Modular programmingpsucmit.pptx
PSPC-UNIT-4.pdf
User Defined Functionscccccccccccccccccccccccccc.pptx
Functions-Computer programming
C concepts and programming examples for beginners
U19CS101 - PPS Unit 4 PPT (1).ppt
Lecture 1_Functions in C.pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
cp Module4(1)
Presentation on Function in C Programming
Functions part1
Fnctions part2
Chapter One Function.pptx
Lecture_5_-_Functions_in_C_Detailed.pptx
Unit-III.pptx
Lecture11 abap on line
Function C programming
functIONS PROGRAMMING CIII II DJDJKASDJKJASD.pptx
C functions by ranjan call by value and reference.pptx
Ad

More from Munazza-Mah-Jabeen (20)

PPTX
Virtual Functions
PPTX
The Standard Template Library
PPTX
Object-Oriented Software
PPTX
Templates and Exceptions
PPTX
Dictionaries and Sets
PPTX
More About Strings
PPTX
Streams and Files
PPTX
Lists and Tuples
PPT
Files and Exceptions
PPT
PPTX
PPT
Repitition Structure
PPTX
Inheritance
PPTX
Operator Overloading
PPT
Memory Management
PPTX
Arrays and Strings
PPTX
Objects and Classes
PPTX
PPTX
Structures
PPTX
Loops and Decisions
Virtual Functions
The Standard Template Library
Object-Oriented Software
Templates and Exceptions
Dictionaries and Sets
More About Strings
Streams and Files
Lists and Tuples
Files and Exceptions
Repitition Structure
Inheritance
Operator Overloading
Memory Management
Arrays and Strings
Objects and Classes
Structures
Loops and Decisions

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
RMMM.pdf make it easy to upload and study
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Cell Types and Its function , kingdom of life
PPTX
Pharma ospi slides which help in ospi learning
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Microbial diseases, their pathogenesis and prophylaxis
Insiders guide to clinical Medicine.pdf
Renaissance Architecture: A Journey from Faith to Humanism
RMMM.pdf make it easy to upload and study
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Structure & Organelles in detailed.
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
human mycosis Human fungal infections are called human mycosis..pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Computing-Curriculum for Schools in Ghana
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Cell Types and Its function , kingdom of life
Pharma ospi slides which help in ospi learning
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf

Functions

  • 2. 12/12/2020 2 Introduction C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined functions. printf and scanf belong to the category of library functions. We have also used other library functions such as sqrt, cos, strcat, etc. The main distinction between these two categories is that library functions are not required to be written by us whereas a user – defined function has to be developed by the user at the time of writing a program. Some Characteristic of modular programming are: 1. Each module should do only one thing. 2. Communication between modules is allowed only by a calling module. 3. A module can be called by one and only one higher module 4. No communication can take place directly between modules that do not have calling – called relationship 5. All modules are designed as single – entry, single – exit systems using control structures
  • 3. 12/12/2020 3 1. Every program must have a main function to indicate where the program has to begin its execution. While it is possible to code any program utilizing only main function. It leads to a number of problems. 2. The program may become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult. 3. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms called ‘functions’ are much easier to understand, debug, and test. 4. The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited. 5. It is easy to locate and isolate a faulty function for further investigations. 6. A function may be used by many other programs. Need for User – Defined Functions
  • 4. DEFINITION A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program. • A function is named • A function is independent. • A function performs a specific task. • A function can return a value to the calling program. 12/12/2020 4
  • 5. Parts of a Function • FUNCTION DECLARATION • FUNCTION DEFINITION • FUNCTION INVOCATION (FUNCTION CALL) 12/12/2020 5
  • 6. FUNCTION DEFINITION SYNTAX 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 Statements 6. A Return statement All the six elements are grouped into two parts namely, 1. Function header (First three Elements) 2. Function Body (Second three Elements) function_type function_name(parameter_list) { local variable declaration; executable statement_1; executable statement_2; --------------------------------- --------------------------------- return statement; } Example: float mul ( float x, float y) { float result; result = x * y; return (result); } 12/12/2020 6
  • 7. FUNCTION PROTYPING OR FUNCTION DECLARATION • A function prototype is a very important feature of modern C programming • It must be added to a C program just before the main function, if we call that function before defining it • It tells the compiler what type of value the function returns, numbers and types of parameters, and order in which these parameters are expected. • There is no need for a prototype if the function is called after its definition 12/12/2020 7
  • 8. FUNCTION DECLARATION SYNTAX 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. 1. Function type (return type) 2. Function name 3. Parameter list 4. Terminating semicolon The general format is Function_type function_name(parameter_list); Example: float mul (float x, float y); 12/12/2020 8
  • 9. Function Prototype 12/12/2020 9 Function Definition A simple format of a C function definition is as follows: return-value-type function-name(parameters) { Declarations; Statements; Return (expression); }
  • 10. S. No. Function prototype Function definition 1. It declares the function. It defines the function 2. It ends with a semicolon. It doesn’t end with a semicolon. 3. Declaration need not include parameters. Definition should include names for the parameters. 12/12/2020 10 Difference Between Function Prototyping and Function Definition
  • 12. Function Terminologies Local and global variables • Local: a variable defined inside a function • Global: a variable defined outside of functions S. No. Local Variables Global Variables 1. These are declared within the body of the function. These are declared outside the function. 2. These variables can be referred only within the function in which it is declared. The values of the variables disappear once the function finishes its execution. These variable can be referred from any part of the program value of variables disappear only after the entire execution or the program. 12/12/2020 12
  • 13. Formal and Actual Parameters • In C, there are two types of parameters • Formal parameters appear in the prototype and definition, and are representative of the data types the function expects to receive • Actual parameters appear only in a function call and are the actual data passed 12/12/2020 13
  • 14. Example #include <stdio.h> void MyFun( int ); Formal Parameter int main( void ) { int x=3; printf( “x has a value of %d”, x); MyFun( x ); Actual Parameter printf( “x has a value of %d”, x); return 0; Parameter Passing } void MyFun( int x ) Formal Parameter { printf( “x has a value of %d”, x); x = 77; printf( “x has a value of %d”, x); } 12/12/2020 14
  • 15. Function prototype and definition #include <stdio.h> int mod(int , int); /* Function Prototype */ void main() { printf("The mod is: %d ", mod(4,5)); } /* Function Definition */ int mod(int x, int y) { return x % y; } 12/12/2020 15
  • 16. CATEGORIES OF FUNCTIONS Category 1: Functions with no arguments and no return values. Category 2: Functions with arguments and no return values. Category 3: Functions with arguments and one return value. Category 4: Functions with no arguments but return a value. Category 5: Functions that return multiple values. 12/12/2020 16
  • 17. Function with No return type and No arguments void main() { ……. ……. ……. func1(); ……. } 12/12/2020 17 void func1() { ……. ……. ……. ……. }
  • 18. #include<stdio.h> void add(); void main() { add(); } void add() { int a,b,c; printf(“enter any two numbers”) scanf(“%d%d”,&a,&b); c= a+b; printf(“the addition of %d and %d is %d”,a,b,c); } 12/12/2020 18
  • 19. Function with No return type and with arguments Void main() { ……. ……. ……. func1(x,y); ……. } 12/12/2020 19 func1(a,b) { ……. ……. ……. ……. }
  • 20. 12/12/2020 20 #include<stdio.h> void add(int,int); void main() { int x,y,c; printf(“enter any two numbers”) scanf(“%d%d”,&x,&y); add(x,y); } void add(int a,int b) { int c; c= a+b; printf(“the addition of %d and %d is %d”,a,b,c); }
  • 21. Function with return type and with arguments void main() { ……. ……. ……. int func1(x,y); ……. } 12/12/2020 21 int func1(a,b) { ……. ……. ……. ……. }
  • 22. #include<stdio.h> int add(int,int); Void main() { int x,y,c; printf(“enter any two numbers”) scanf(“%d%d”,&x,&y); c = add(x,y); printf(“The Result = %d ”,c); } int add(int a ,int b) { int c; c= a+b; return (c); } 12/12/2020 22
  • 23. Function with return type and No arguments void main() { ……. ……. ……. int func1(); ……. } 12/12/2020 23 int func1() { ……. ……. ……. ……. }
  • 24. #include<stdio.h> int add(); Void main() { int c; c = add(); printf(“The Result = %d ”,c); } int add() { int a,b,c; printf(“enter any two numbers”) scanf(“%d%d”,&a,&b); c= a+b; return (c); } 12/12/2020 24
  • 25. Functions that return multiple values #include <stdio.h> void interchange (int *a , int *b) void main() { int i=5,j=10; printf(“Before : I and J value is %d and %d”,I,j); interchange(&i,&j); printf(“After : I and J value is %d and %d”,I,j); } void interchange (int *a, int *b) { int t; t=*a *a=*b *b=t } 12/12/2020 25 O/p: Before : I and J value is 5 and 10 After : I and J value is 10 and 5
  • 26. Function without a prototype #include <stdio.h> int sum(int x, int y) { return x+y; } void main() { printf("The sum is: %d ", sum(4,5)); } 12/12/2020 26
  • 27. Parameter Passing Methods • In C there are two ways of passing parameters to a function Call by Value Call by Reference 12/12/2020 27
  • 28. Call by value Copy of data passed to function Changes to copy do not change original Prevent unwanted side effects This Method copies the value of actual parameters(calling program) into the formal parameters(called program) of the functions. Here the changes of the formal parameters cannot affect the actual parameters. Because only the copy of actual arguments were passed. A function can return only one value per call. 12/12/2020 28
  • 29. Example #include <stdio.h> int cube (int) void main() { int n=5; printf(“Cube of %d is %d”,n,cube(n)); } int cube (int x); { x=x*x*x; return x; } O/p: Cube of 5 is 125 12/12/2020 29
  • 30. Call by reference Function can directly access data Changes affect original It is another way of passing parameter to the functions here the address of arguments are copied into the parameters inside the functions. The address is used to access the actual arguments used in the call. By using this we can make a function to return more the one value(indirectly). 12/12/2020 30
  • 31. Example #include <stdio.h> void interchange (int *a , int *b) void main() { int i=5,j=10; printf(“Before : I and J value is %d and %d”,I,j); interchange(&i,&j); printf(“After : I and J value is %d and %d”,I,j); } void interchange (int *a, int *b) { int t; t=*a *a=*b *b=t } 12/12/2020 31 O/p: Before : I and J value is 5 and 10 After : I and J value is 10 and 5
  • 32. Call by value Vs Call by reference • Call by value Copy of data passed to function Changes to copy do not change original Prevent unwanted side effects • Call by reference Function can directly access data Changes affect original 12/12/2020 32
  • 33. #include <stdio.h> void swap(int, int); void main() { int num1, num2; num1 = 10; num2 = 20; swap ( num1, num2 ); printf("%d %dn", num1, num2); } void swap(int val1, int val2) { int temp; temp = val1; val1 = val2; val1 = temp; } 12/12/2020 33
  • 34. Swap two integers using call by value(cont.) • In the above example, we passed parameters by value, a copy is made of the variable and thus any change made to the parameters val1 and val2 will not be passed back to the main function •The main function will not know anything about the swapping of val1 and val2 Therefore, the output of the above program will be ….? • Normally if we wished to pass back a value we would use return or we would pass the parameters by reference 12/12/2020 34
  • 35. Nested Functions In C , it provides a facility to write one function with in another function.This is called nesting of functions 12/12/2020 35 Main() { --------- func1(); --------- --------- } func1() { --------- func2(); --------- --------- } func2() { --------- --------- --------- --------- }
  • 37. Recursion Recursion is a process of calling the same function itself again and again until same condition is satisfied. This is used for repetitive computation in which each action is satisfied in terms of a previous result •A function can call itself •Directly •Indirectly 12/12/2020 37 Function1() { ----- Function1(); ----- }
  • 38. 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 between performance (iteration) and good software engineering (recursion) 12/12/2020 38
  • 39. Sl.No. Iteration Recursion 1. Iteration explicitly user a repetition structure. Recursion achieves repetition throught repeated function calls. 2. Iteration terminates when the loop continuation condition fails. Recursion terminates when a base case is reached. 3. Iteration keeps modifying the counter until the loop continuation condition fails. Recursion keeps producing simple versions of the original problem until the base case is reached. 4. An infinite loop occurs when the loop step continuation test never becomes false. An infinite loop occurs if the recursion doses not reduce the problem each time in a manner that converges the base case. 5. Iteration normally occurs within a loop so extra memory assignment is omitted. Recursion causes another copy of the function & hence a considerable memory space is occupied. 6. It reduces the processor operating It increases the processor operating 12/12/2020 39 Difference Between Iteration and Recursion
  • 40. Example: fibonacci.c function Fibonacci ( n ) { if ( n is less than or equal to 1 ) then return n else return Fibonacci ( n - 2 ) + Fibonacci ( n - 1 ) } 12/12/2020 40 /* Compute the n-th Fibonacci number, when=0,1,2,... */ long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); }
  • 41. Example: Computation of fib(4) 12/12/2020 41 +fib(2) fib(3) fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 4 4 4 4
  • 42. Example: Computation of fib(4) 12/12/2020 42 fib(2) fib(3)+ fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 2 2 +fib(0) fib(1)
  • 43. Example: Computation of fib(4) 12/12/2020 43 fib(2) fib(3)+ fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 0 0 +fib(0) fib(1) 0
  • 44. Example: Computation of fib(4) 12/12/2020 44 fib(2) fib(3)+ fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 0 0 +0 fib(1) 0
  • 45. Example: Computation of fib(4) 12/12/2020 45 fib(2) fib(3)+ fib(4) + fib(1)0 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 220
  • 46. Example: Computation of fib(4) 12/12/2020 46 fib(2) fib(3)+ fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 1 1 + fib(1)0 1
  • 47. Example: Computation of fib(4) 12/12/2020 47 fib(2) fib(3)+ fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 1 1 + 10 1
  • 48. Example: Computation of fib(4) 12/12/2020 48 fib(2) fib(3)+ fib(4) +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 0 21
  • 49. Example: Computation of fib(4) 12/12/2020 49 1 fib(3)+ fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 0 +0 1 21
  • 50. Example: Computation of fib(4) 12/12/2020 50 + fib(3) fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 4 4 4 4 1 +0 1 1
  • 51. Example: Computation of fib(4) 12/12/2020 51 + fib(3) fib(4) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 3 3 3 3 1 +0 1 +fib(1) fib(2)
  • 52. Example: Computation of fib(4) 12/12/2020 52 + fib(3) fib(4) 1 +0 1 +fib(1) fib(2) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 1 1 1
  • 53. Example: Computation of fib(4) 12/12/2020 53 + fib(3) fib(4) 1 +0 1 +1 fib(2) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 1 1 1
  • 54. Example: Computation of fib(4) 12/12/2020 54 + fib(3) fib(4) 1 +0 1 +1 fib(2) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 3 3 3 31
  • 55. Example: Computation of fib(4) 12/12/2020 55 + fib(3) fib(4) 1 +0 1 +1 fib(2) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 2 2 +fib(0) fib(1)
  • 56. Example: Computation of fib(4) 12/12/2020 56 + fib(3) fib(4) 1 +0 1 +1 fib(2) +fib(0) fib(1) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 0 0 0
  • 57. Example: Computation of fib(4) 12/12/2020 57 + fib(3) fib(4) 1 +0 1 +1 fib(2) +0 fib(1) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 0 0 0
  • 58. Example: Computation of fib(4) 12/12/2020 58 + fib(3) fib(4) 1 +0 1 +1 fib(2) +0 fib(1) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 2 20
  • 59. Example: Computation of fib(4) 12/12/2020 59 + fib(3) fib(4) 1 +0 1 +1 fib(2) +0 fib(1) long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 1 1 1
  • 60. Example: Computation of fib(4) 12/12/2020 60 + fib(3) fib(4) 1 +0 1 +1 fib(2) +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 1 1 1
  • 61. Example: Computation of fib(4) 12/12/2020 61 + fib(3) fib(4) 1 +0 1 +1 fib(2) +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 2 20 1
  • 62. Example: Computation of fib(4) 12/12/2020 62 + fib(3) fib(4) 1 +0 1 +1 1 +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 2 2 2 20 1
  • 63. Example: Computation of fib(4) 12/12/2020 63 + fib(3) fib(4) 1 +0 1 +1 1 +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 3 3 3 31 1
  • 64. Example: Computation of fib(4) 12/12/2020 64 + 2 fib(4) 1 +0 1 +1 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 3 3 3 31 1 +0 1
  • 65. Example: Computation of fib(4) 12/12/2020 65 + 2 fib(4) 1 +0 1 +1 1 +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 4 4 4 41 2
  • 66. Example: Computation of fib(4) 12/12/2020 66 + 2 3 1 +0 1 +1 1 +0 1 long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); } 4 4 4 41 2
  • 67. Example: Computation of fib(4) 12/12/2020 67 + 2 3 1 +0 1 +1 1 +0 1 Thus, fib(4) returns the value 3
  • 68. Example: fibonacci.c 12/12/2020 68 int main(void) { int number; printf("Enter number: "); scanf("%d", &number); printf("Fibonacci(%d) = %ldn", number, fib(number)); return 0; } Sample main() for testing the fib() function:
  • 69. Scope Where can you use a variable which is declared in a function? • In that function only • Not in a calling function • Not in a called function 12/12/2020 69
  • 70. Scope: Local Variables • Formal parameters: only accessible whilst a function is executing • Variables declared in a function body: only accessible whilst the function is executing • In fact, this is true of every block in a program 12/12/2020 70
  • 71. Exercise • Write a program to find the factorial using a functions. • Write a program to find the value of x n. For any given values of x and n . 12/12/2020 71
  • 73. Arrays to the function in One dimensional • An entire array can be transferred to a function as a parameter. • Actual parameter : the array name is enough without subscripts to transfer an array. • Formal parameter : must be declared as an array to receive the values from main program. syntax : 12/12/2020 73 void func(int,int[]) main() void func(int x, int arr[10]) { { int a[10],i; ………… func(i,a); ………… } }
  • 74. 12/12/2020 74 Three Rules of Pass an Array to a Function 1. The function must be called by passing only the name of the array. 2. In the function definition, the formal parameter must be an array type; the size of the array does not need to be specified. 3. The function prototype must show that the argument is an array.
  • 75. Sample program #include<stdio.h> #inlcude<conio.h> void add(int[]) void main() { int i,arr[10]; printf(“Enter 10 elements of the array”); for(i = 0;i<10;i++) scanf(‘%d”,&arr[i]); add(arr); } 12/12/2020 75 void add(int a[]) { int i,sum = 0; for(i = 0;i<10;i++) sum = sum+a[i]; printf(“ the value of sum is %d”, sum); }
  • 76. Changing an Array in a Function #include <stdio.h> void fun ( int [ ] ) int main(void) { int array[ ] = { 1 , 2 , 3 , 4 , 5 }; fun ( array ); printf ( “%d” , array [ 3 ] ); Will print 20 return 0; } void fun ( int x[ ] ) { x[3] = 20; return; } 12/12/2020 76
  • 77. Largest of Given Numbers 12/12/2020 77 #include<stdio.h> void main() { float largest(float a[ ], int n); float value [4] = {2.5,-4.75,1.2,3.67}; printf("%fn",largest(value,4); } float largest(float a[ ], int n) { int i; float max; max = a[0]; for(i=1; i<n; i++) if(max < a[i]) max = a[i]; return(max); }
  • 78. Sorting of Given Numbers 12/12/2020 78 #include<stdio.h> void main() { int i; int mark[5] = {40,90,73,81,35}; printf("Marks before sortingn"); for(i = 0;i<5;i++) printf("%d",marks[i]); printf("nn"); sort(5,marks); printf("Marks after sortingn"); for(i = 0;i<5;i++) printf("%4d",mark[i]); printf("n"); }
  • 79. Sorting of Given Numbers Conti…. 12/12/2020 79 void sort(int m,int x[]) { int i,j,t; for(i=0;i<m-1;i++) for(j=i+1;j<m;j++) if (x[i] > x[j]) { t = x[i]; x[i] = x[j]; x[j] = t; } }
  • 80. Arrays to the function inTwo dimensional 12/12/2020 80 Like simple arrays, we can also pass multidimensional array to functions. The approach is similar to the one we did with one – dimensional arrays. The rules are simple. 1. The function must be called by passing only the array name. 2. In the function definition, we must indicate that the array has two dimensions by including two sets of brackets. 3. The size of the second dimension must be specified. 4. The prototype declaration should be similar to the function header.
  • 81. Calculates the average of the values in a two – dimensional matrix 12/12/2020 81 #include<stdio.h> void main() { int M = 3, N = 2; double average (int [] [N],int,int); double mean; int matrix [M][N] = {{1,2},{3,4},{5,6}}; mean = average(matrix, M, N); printf("The Mean of the Two Dimensional Array is: %f",mean); } double average(int x [ ] [N],int M,int N) { int i,j; double sum = 0.0; for(i=0;i<m;i++) for(j=1;j<N;j++) sum = sum + x[i][j]; return (sum / (M * N); }
  • 82. Passing Strings to Functions 12/12/2020 82 The Strings are treated as character arrays in C, 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. Example: void display(char item_name[]) { ---------------- ---------------- } 2. The function prototype must show that the argument is a string. For the above function definition, the prototype can be written as void display(char str[ ]) 3. A call to the function must have a string array name without subscripts as its actual arguments. Example: display(names); where names is a properly declared string array in the calling function.