4. โข You can divide up your code into separate functions. Logically
the division is such that each function performs a specific task.
โข A function can also be referred as a method or a sub-routine or
a procedure.
Functions
Module 4 4
A function is a group of statements that together perform a task.
5. 1. Function Prototype (function declaration)
2. Function Definition
3. Function Call
Elements of User Defined Function
Module 4 5
6. โข A function declaration tells the compiler about a function
name and how to call the function.
โข Syntax:
โข Example:
void xyz(int, char,float);
1.
2.
1. Function Declaration
Module 4 6
returntype function_name (Parameter List);
7. โข Contains all the statements to be executed.
2.Function Definition
Module 4 7
returntype function_name (parameter list)
{
//body of the function
}
9. โข When a program calls a function, the program control
is transferred to the called function.
3. Function Call
Module 4 9
function_name(arguments list);
11. int max(int num1,int num2);
void main()
{
int a=100,b=200,ret;
ret=max(a,b);
printf(โthe max value is %dโ,ret);
}
int max(int num1,int num2)
{
int result;
If(num1>num2)
result=num1;
Else result=num2;
return result;
}
Example
Module 4 11
13. 1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
Categories of User-defined Functions
Module 4 13
14. 1. Function with no arguments and no return value
Module 4 14
Function Call
15. Module 4 15
2. Function with no arguments and a return value
18. โข Call by Value
โข Call by Reference
Methods of calling a Function
Module 4 18
19. โข In call by value method, the value of the variable is passed to
the function as parameter.
โข The value of the actual parameter can not be modified by
formal parameter.
โข Different Memory is allocated for both actual and formal
parameters.
Call by value method
Module 4 19
20. #include<stdio.h>
// function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
printf(" values before swap m = %d n and n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" nvalues after swap m = %dn and n = %d", a, b);
}
Example
Module 4 20
21. โข Pass Individual Array Elements
โข Pass Arrays to Functions
โ Function Prototype: void pass(int []);
โ Function call: pass(a);
โ Function definition:
โข void pass(int b[])
โ {for(int i=0;i<3;i++)
โ printf("%dn",b[i]);}
Pass arrays to a function in C
Module 4 21
//pass second and third elements to display()
display(ageArray[1], ageArray[2]);
Function Definition
void display(int age1, int age2)
{ // code }