Sunday, 24 September 2017

Sum of series using recursion

Q : Define recursion. Write a complete program to evaluate the given series using recursive function sum( ). Here n is user dependent.
1 + 2 + 3 +…+ n

Solution : 

As we C language is known as building block of functions. This means everything in c language is achieved through a function. In C language there is not any restriction to call a function you can call a function from anywhere No matter of scope.


Recursion is a way of calling a function in which a function is called by itself. So there is a need to manage calling sequence otherwise it become infinite. System internally manages a stack to trace function call turn.

Recursive Function


#include<stdio.h>
int sum(int);
void main()
{
     int n;
     printf("Enter number>> ");
     scanf("%d",&n);
     printf("\n\tSum=%d",sum(n));
}
int sum(int n)
{
     if(n==1)
          return(1);
     else
          return(n+sum(n-1));
}