Wednesday, August 10, 2011

C Programming: User define functions

A function in C can be taken as function in mathematics like sin(x), x^2+2x+6 etc. You supply the value of variable x and it gives its corresponding functional value. You can supply any value of x and it gives corresponding functional value. C equivalent syntax for these functions is

float f(float x){
  return x*x+2*x+6;
}

It takes value of x as input and calculates the functional value and at last returns it. Are they equivalent??


Why functions are needed?


Suppose you need to calculate the factorial of 5 in one portion of your program to do certain problem for example to find permutation, then must probably you write a code to calculate factorial of 5 as

int fact=1;
int i;
for(i = 5; i > 0; i--){
     fact*=i;
}
 
It gives the factorial of 5. Now you again need factorial of 10(say) in another portion of your program. Then what you do? Do you write another code for 10? again you need factorial of 7, then do you write code again? Writing code for every factorial makes program very lengthy. Now you can make a function that takes a number of which factorial is to be calculated. It process that number and calculate the factorial and finally returns it to original position. You can pass any positive number and it calculates factorial of every number you supply by only one code. And the code will be…
int fact(int x){
   int i; //local variable
   factorial = 1;  //initialization
   for(i=x;i>0;i--){
     fatorial *= x;
   }
   return fact
}

Now to calculate value 5! you can simply call this function as..

int result = fact(5);

Again if you need 7! you can call like fact(7) and so on. So only one code calculates the factorial of as many as numbers you supply. This is the main need of function.


General Syntax for function definition

return_type function_name(parameter list){
local variable declaration;
executable statement1;
executable statement2;
.
.
.
.
return statement
}

General Syntax for function call

function_name(parameter list);




The solution of different problems is given in successive posts

No comments:

Post a Comment