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.

amari ♥ 0 Newbie Poster

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.

Shankye 36 Junior Poster

Post your code .. We will help to solve probs ..

sharathg.satya -10 Posting Whiz in Training

you can use the sum to 'n' terms formula to get your required result

Edited by sharathg.satya because: * n/a *

Shankye 36 Junior Poster

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;
}
```

sharathg.satya -10 Posting Whiz in Training

we have to decrement the value of 'i' so that it terminates when it becomes 0

Shankye 36 Junior Poster

Oops sorry for the mistake..

Correct code may be like this

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

Hope code is correct now ..

sharathg.satya -10 Posting Whiz in Training

haah now its right and thanks for correcting

Shankye 36 Junior Poster

:-)

sharathg.satya -10 Posting Whiz in Training

i.e.., n*(n+1)/2

even using this we can do the problem of solving the sum of n terms

Shankye 36 Junior Poster

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

Mark it solved if problem solved ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.