Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Muhammad Suffian
WHY FUNCTIONS???
To reduce the size of the main program
To make the program easier to understand and
even easier to write
Program divided in modules
The main logic of the program (Main function) is neat
for visualization
Reusability
Modules (functions) can be reused multiple times, by
simply making a call to a function. (Instead of writing
the function again and again, just call the name to
use the function.
If reused with different variables/values, the variable
names/values are to be provided at the time of calling
a function.
EXAMPLE
#include <stdio.h>
int main()
{
add(); // function call
return 0;
}
/* function definition */
void add()
{
int num1, num2;
int sum = 0;
num1=0;
num2=0;
printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);
Function Definition
AFTER main(), the definition of the function is
provided
Function Call
In main the function is called where ever required
HOW FUNCTION WORKS???...
#include <stdio.h>
int main()
{
add();
return 0;
}
void add()
{
int num1 =0 , num2 =0 , sum = 0;
printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);
int main()
{
int num1=0,num2=0;
int result;
printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);
result = add(num1,num2);
printf("\nResult : %d",result);
return(0);
}
int main()
{
int num1=0,num2=0;
int sum, diff;
printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);
sum = add(num1,num2);
diff = sub(num1, num2);
printf("\nsum : %d",sum);
printf("\ndifference : %d",diff);
return(0);
}