Saturday, December 15, 2018

Function and Recursion

Function is a module that has various kinds of commands in it, we can call the function if and only if the function is above the caller function.


Recursion is the application of a function that calls itself, is like a loop (while) but its work is heavier than looping, based on the base case and best case.




Advantages of using Functions:
  • Top-down design with sub goal, huge program divided into smaller modules
  • Can be done by more than one developer/ programmer
  • Easier to debug, as logical flow is easy to follow and easier to pin point errors
  • Modification can be done without affecting overall codes
  • Easier to document

The library that we included in C are called functions as well, stdio.h, math.h. They have pre-built functions that we just need to call.


Example of function:
#include

int maximum (int x, int y){
      int max = x;
      if ( y > max) max = y;
      return max
}

void main () {
     int a,b;
     printf("Input 2 even values : ");
     scanf("%d %d", &a, &b);
     printf("Largest value : %d\n",maximum(a,b));
}



The recursive function consists of two components:

Base Case:
Return value (constant) without calling the next recursive call.

Reduction step:
Sequence of the input value that corresponds to the base case.



Example of recursion:


Factorial - Recursive
long factor (int n) 
{
    if(n==0) return (1); <<<<<Base case
      else return(n * factor(n-1));<<<< Reduction Step
}



Although recursive code is more concise it needs more memory consumption and takes longer time.




By :Steven
2201852132
Computer Science and Statistics

No comments:

Post a Comment