Function and Recursion


Function
Function in C is related to modular programming. To implement modules in C, we use function to call sub-program of a group of statements when necessary.
In C, there are two types of function. First one is library function(printf, scanf) and the second one is user-defined function(self-defined).
The construct of user-defined function is :
return-value-type function name(parameter-list){
          statements};

Example:
int even(int x){
   if(x % 2 == 0){
         return 1;
   }
   else{
         return 0;
   }
};

int main(){
   #include<stdio.h>
   int x;
 
   scanf("%d", &x);
   even(x);
   if(even(x) == 1){
        printf("It's even\n");
   }
   else{
        printf("It's not even\n);
   }
   return 0;
}

In the example above, to call a function in main you just need to type the function name and include the parameter. The parameter used above is what we call a local variable. A local variable is only recognized in the function and can't be used in other function if we don't pass it. Another type of variable is global variable. Global variable is recognized by all function and declared at the top.



Recursion
Recursive is a function that call itself. It has two components : base case(used to end the call) and reduction step(repeated sequence that will eventually reach the base case).
Example :
int fibonacci(int x){
   //base case
   if(x == 0){
        return 0;
   }
   else if(x == 1)
        return 1;
   //reduction step
   }
   else{
        return fib(n-2) + fib(n-1);
   }

While using recursive, you need to know that recursive takes longer time and use more memory. Therefore, consider what your program need before using recursive or using iterative.

Comments