Not Yet Answered # recursion - how to calculate sum?

vmanes 1,165 kamlesh_ag07 vmanes 1,165 iamthwee 1,547 ChaseVoid 30 Discussion Starter krizz vmanes 1,165 ChaseVoid 30 Salem 5,138 vmanes 1,165 ChaseVoid 30 Narue 5,707 ChaseVoid 30 anirudhbsg -2 Narue 5,707 Discussion Starter krizz anirudhbsg -2

0

Assuming you understand how to write a recursive function, you need to establish what the base case is for this problem - when a parameter for the current term passed in is equal to the upper limit (10 in this case, but best also passed as a parameter for flexibility of use). Rather than the usual decreasing value passed in (the 10-1 version), your current term will be 1 in the first call, 2 in the next, and so on.

Val

0

according to me the code can be writen in this way.

```
#include <iostream>
#include <conio>
int sum(int);
int x;
void main()
{
int n ;
cin >> n ;
sum(n) ;
cout<<" the sum is"<<x ;
getch();
}
int sum(int a)
{
if(a)
{
return sum(a-1)+a;
}
}
```

0

It can be written that way, but it's not correct. It doesn't even compile.

Once you fix the two problems in your preprocessor directives, you'll find it is not a correct solution.

Once you've corrected the problem in main that causes you to not even see the answer your sum( ) function returns, note that you have not solved the original problem. Your function works in the 10 9 8... direction.

Your `if( a )`

is clever approach, however it leaves your function with a warning of "not all control paths are followed."

You should test code before posting it to the world.

0

>it should be 1+2+...+9+10 and not 10+9+...+2+1

But it gives you exactly the same answer, and all you are asking for is the end total right?

0

The quest here is not to get the result, but to get that scenario. If you just wanted to get the sum then this is suffice :

```
#include<iostream>
using namespace std;
int Sum(int s)
{
int result;
if( s == 1 )
return 1;
else
{
result = Sum(s-1) + s;
return result;
}
}
int main()
{
int n = 0;
cout<<"Enter a limit : ";
cin>>n;
cout<<"The sum of numbers up to "<<n<<" is "<<Sum(n);
cin.ignore();
cin.get();
}
```

But we want to get the result such that it calculates from 1 till the limit.

```
for ( int i = 1; i < limit; i++ )
sum += i;
```

We want that scenario with recursion. I've trying to figure it out, but I can't :(

0

The end total can be found easily by calculating from 10+9+...+2+1 but i am more interested in the scenario as one of my friends has already said..ie. I need it to process from 1 to n and not n to 1.

>it should be 1+2+...+9+10 and not 10+9+...+2+1

But it gives you exactly the same answer, and all you are asking for is the end total right?

0

ChaseVoid's code gives a good implementation of the normal (1+2+3...) method of recursively solving this problem. Reread my first comments, and you should be able to modify that function to make it solve in the desired way.

Val

0

> iamthwee : You don't need to figure it out as it isn't your homework.

Does it really matter whether it's my homework or not. We have a really interesting question here and trying to solve it is fun. You might know this answer, but I don't so I tried to solve it. And I'm really glad I did.

I was thinking too much into the matter, and the correction was just the use of global declaration.

```
#include<iostream>
using namespace std;
int n = 0;
int Sum(int s)
{
int result;
if( s == n )
return n;
else
{
result = Sum(s+1) + s;
return result;
}
}
int main()
{
cout<<"Enter a limit : ";
cin>>n;
cout<<"The sum of numbers up to "<<n<<" is "<<Sum(1);
cin.ignore();
cin.get();
}
```

this is what I got. But I'm still not so sure, when I simulated this program I found that first it increases the s from 1 to n and then it decreases from n -1 and also adds it to the result. While the program before, is the reverse. I haven't done much recursion, but still.. it seems weird to me. May I have some expert advice on this matter?

0

> I was thinking too much into the matter, and the correction was just the use of global declaration.

Why not pass the limit as another parameter?

0

First, your `int n = 0;`

is a global variable; not a recommended practice in most cases.

As I mentioned previously, your recursive function will need to know the current value it's to process (your parameter s) and the limit (your global var n). So simply add a parameter to the function that will be the upper limit value entered by the user.

What you see as the values going up (as desired) then down is the way that recursive functions work. It's kind of like a watch spring being wound up, then unwinding when released. (Sorry, bad analogy, nobody knows how a mechanical watch works any more!)

Why is the global variable not a good idea? It can be modified by any function in a program, and thus you have no real control over it. It can make debugging difficult, and it reduces the ability to reuse code in future projects. Use of global variables needs to be very well thought out and very well documented.

Val

0

>Why not pass the limit as another parameter?

Well I could have done that, but then here `result = Sum(s+1) + s;`

I would have to pass two parameter as well. As I mentioned earlier, I don't know much in depth about recursion, so have no idea how or what to pass there. if you know, please tell me.

0

>I don't know much in depth about recursion, so have no idea how or what to pass there.

It doesn't really matter that the function is recursive. Just pass the parameter along without changing it and everything will be fine:

```
#include<iostream>
using namespace std;
int Sum(int s, int n)
{
int result;
if( s == n )
return n;
else
{
result = Sum(s+1, n) + s;
return result;
}
}
int main()
{
int n;
cout<<"Enter a limit : ";
cin>>n;
cout<<"The sum of numbers up to "<<n<<" is "<<Sum(1, n);
cin.ignore();
cin.get();
}
```

0

> Just pass the parameter along without changing it

Oh! i see now, since inside the Sum() function we are not manipulating variable n, it'll be. Thank you.

0

I need help with the following:

How do we calculate the sum of consecutive numbers from 1 to n and not from n to 1 by using recursion.

Eg. if n = 10

it should be 1+2+...+9+10 and not 10+9+...+2+1.

see its very simple you just need to use one for loop statement:

for(int i=0;i<n;i++)

(sum=sum+i;

}

0

>see its very simple you just need to use one for loop statement

If it's so simple, why did you get it wrong? Read the post you quoted again. It says "by using recursion". A loop isn't recursion, it's iteration.

0

Thankz for your solution ChaseVoid and to all. This site is amazing. It helped me alot as i have just started taking programming units in uni.

0

If it's so simple, why did you get it wrong? Read the post you quoted again. It says "by using recursion". A loop isn't recursion, it's iteration.

yes i really apologize , i just missed that the discussion is on recursion and not iteration

i will definetely take care of this thing in future..

sorry again.....

This article has been dead for over six months. Start a new discussion instead.

Recommended Articles

Hi. I have a form with list box : lst_product, datagridview : grd_order and button: btn_addline. lst_product has a list of product ids selected from database (MS Acess 2013) , grd_order is by default empty except for 2 headers and btn_addline adds rows to grd_order.

btn_addline :

`Private Sub btn_addline_Click(ByVal ...`

I don’t want at this stage work on a big separate project as I've already got plenty ...

I am writing a java program that needs to execute shell commands, so I wrote a function that would take the command to execute as a string (ie: "mkdir ~/Folder1") and execute that command with the shell. Here is the function:

```
try
{
Runtime run = Runtime.getRuntime();
Process pr = ...
```