0

i need help with the following:

make a program that gets the summation of a given number e.g. 4+3+2+1

implement it using both iteration and recursion

ex. enter a positive number: 4
the sum is 10.

3
Contributors
9
Replies
13
Views
6 Years
Discussion Span
Last Post by Shankye
0

Recursion may be like this

sum(int n)
{
          if(n==0)
             return 0;
          else
             return n+sum(n-1);
}

iteration may be like this

while(i != 0)
{
      sum += i;
}
0

Oops sorry for the mistake..
Correct code may be like this

while(i != 0)
{
      sum += i;
      i--;
}

Hope code is correct now ..

0

we also have a direct formula to calculate sum of n terms
i.e.., n*(n+1)/2
even using this we can do the problem of solving the sum of n terms

0

Ya but he want a recursion and iteration based program ..

Mark it solved if problem solved ..

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.