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.
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.
Post your code .. We will help to solve probs ..
you can use the sum to 'n' terms formula to get your required result
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;
}
the loop in case of iteration is infinite
we have to decrement the value of 'i' so that it terminates when it becomes 0
Oops sorry for the mistake..
Correct code may be like this
while(i != 0)
{
sum += i;
i--;
}
Hope code is correct now ..
haah now its right and thanks for correcting
:-)
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
Ya but he want a recursion and iteration based program ..
Mark it solved if problem solved ..
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.