RECURSION

RECURSION :

 In Computer Programming, when a function calls itself either directly or indirectly it is called Recursive Function and the process is called Recursion.

Typically the function Performs some part of the task and the rest is delegated to the recursive call of the same function, hence, there are multiple instances of same function each performing some part of the overall task.Function stops calling itself when a terminating condition is reached.


Points to note on recursion:

  1. Recursion always having a terminating condition(else it will be infinite recursion).
  2. Recursive function performs some part of task and delegate rest of it to the recursive call. 

Compute sum of first n positive numbers :

#include <stdio.h>
int main()
{
     int n,total;
     printf("Enter a number to compute the sum of first n positive \n");
     scanf("%d",&n);
     total=sum(n);
     printf("%d is the sum of first %d numbers",total,n);
     return 0;
}
int sum(int n)
{
      return n==0?0:((n==1)?1:(n+sum(n-1)));
}

Output:


Enter a number to compute the sum of first n positive 
5
15 is the sum of first 5 numbers



Comments

Popular posts from this blog

Program to know the range of short signed integer

Finding the second largest in an array