Why we should use the function?
1. Function reduces the redundancy of code.
Example: 1
Write a c program to find the sum of: 1! /5+ 2! /4+ 3! /3+ 4! /2+ 5! /1 without using function (Except main function). Where! Symbol indicates factorial of any number.
Example: 2
Write the same code using function?
More example click here.
2. It breaks down a large program in small modules to improve readability, portability as well as makes the program easy to debug.
Example: 1
Write a c program to find the sum of: 1! /5+ 2! /4+ 3! /3+ 4! /2+ 5! /1 without using function (Except main function). Where! Symbol indicates factorial of any number.
void main(){
int num, sum=0;
int fact1,fact2,fact3,fact4,fact5;
fact1=fact2=fact3=fact4=fact5=1;
num=0;
while(num<=0){
fact1 =fact1+fact1*num;
num++;
}
num=0;
while(num<=1){
fact2 =fact2+fact2*num;
num++;
}
num=0;
while(num<=2){
fact3 =fact3+fact3*num;
num++;
}
num=0;
while(num<=3){
fact4 =fact4+fact4*num;
num++;
}
num=0;
while(num<=4){
fact5 =fact5+fact5*num;
num++;
}
clrscr();
sum=fact1/1+fact2/2+fact3/3+fact4/4+fact5/5;
printf("%d",sum);
getch();
}
Example: 2
Write the same code using function?
void main(){
int sum;
sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5;
clrscr();
printf("%d",sum);
getch();
}
int fact(int x){
int num=0,fact=1;
while(num<=x-1){
fact =fact+fact*num;
num++;
}
return fact;
}
Compare the example one and two and find out the importance of function. You will find out function reduces the repetition of same code.More example click here.
2. It breaks down a large program in small modules to improve readability, portability as well as makes the program easy to debug.
No comments:
Post a Comment