facebook like button

11 September, 2011

programs to find sum of first n natural numbers with recursion

The need: 
     This is a simple programs to find sum of first n natural numbers with recursion explaining the example2 of previous to previous post. We know that natural numbers form a series whose first term is 1 and T(n)=n and this is obvious that sum upto n term = sum upto n-1 terms + nth term.
The code: 
---------------------------------------------------------


#include<stdio.h>
int get_sum(int x);

int main()
{
    int n,Sn;
    printf("Enter upto which number do you want sum?\n");
    scanf("%d",&n);
    Sn=get_sum(n);
    printf("S(%d) = %d\n",n,Sn);
    return 0;
}

int get_sum(int x)
{
    int SUM;
    if(x==1)
      SUM=1;
    else
      SUM= get_sum(x-1) + x;
    return SUM;
}
---------------------------------------------------------

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply