Friday, October 30, 2009

Running sum of first 25 numbers

Write a recursive function to obtain the running sum of first 25 natural numbers.


void main()
{
int d,e;
d=25;
e=naturaln(d);
printf("\nThe sum of the first %d digits is %d",d,e);
}

naturaln(int x)
{
int a;
if(x==1)
return(1);
else
{
a=x+naturaln(x-1);
return(a);
}


}

9 comments:

  1. in this recursive function,will not the value of x
    be negative after it has reached zero?what if i write

    if(x==25)
    return(25);
    else
    a=x+natural(x+1);
    return(a);
    }

    ReplyDelete
  2. It'll never reach zero because after reaching 1 the program comes out of the function

    ReplyDelete
  3. Will it be wrong if I write. {
    int a;
    if(x==0)
    return(1);

    ReplyDelete
  4. Yes it will be wrong becoz it will add an extra 1 to the series

    ReplyDelete
  5. I just want to know what if I write
    int getsum ( int n)
    { int sum=0;
    if (n==25)
    return sum;
    sum =n+getsum (++n);
    return (sum);
    }

    How it will add 25 to the series when it will return 0 for getsum (25);

    ReplyDelete
  6. int getsum(int);
    int main()
    {
    int s;
    s=getsum(0);
    printf("the sum of first 25 natural
    is %d\n",s);
    return 0;
    }
    int getsum(int n)
    {
    int sum=0;
    if(n==25);
    return sum;
    sum=n+getsum(++n);
    return (sum);
    }

    ReplyDelete
  7. int getsum(int);
    int main()
    {
    int s;
    s=getsum(0);
    printf("the sum of first 25 natural
    is %d\n",s);
    return 0;
    }
    int getsum(int n)
    {
    int sum=0;
    if(n==25);
    return sum;
    sum=n+getsum(++n);
    return (sum);
    }

    ReplyDelete