Strange Little Problem ! ?

Hi!

I'm new to C++, and I'm having some trouble with a code. It's supposed to return the value of 1, when instead it return values of 6000+.

I'm using Bloodshed Dev C++. Thank you ;)



#include <iostream>

using namespace std;

int value(int n)
{
if (n > 1)
{
value(n-1);
}
else
{
return n;
}
}

int main()
{
cout << value(20) << endl;

system("Pause");
return 0;
}
This looks fine to me.
I think you want to do this :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

//prototype
int value(int n);

int main()
{
	cout << value(20) << endl;

	system("Pause");
	return 0;
}


int value(int n) // decreases n by 1 as long as it's bigger then 1
{
	while (n > 1) 
		n--;
	
	return n;
}


hope it helped :)
First, there's nothing wrong with defining the function before main() and skipping the prototype. Second, I would assume the point of the exercise is to use recursion.

The problem with the OP's function is that it does not return value(n - 1):

1
2
3
4
5
6
7
8
9
10
11
int value(int n)
{
    if (n > 1)
    {
        return value(n - 1);
    }
    else
    {
        return n;
    }
}
Last edited on
Wasn't really forcing him to use a prototype, it's just that I prefere to use it :)

And may I ask you why , if in your code return value (n--); won't work as a replacement for return value(n - 1); ? Can't really figure it out atm :) 'cause for as far as I read my tutorial it should work.
n-- decrements n but returns the original value of n. So if you used that in the above function you'd always be passing the original n. You could say return value(--n);, however, but I don't see a reason to assign n a new value if it's not going to be used anyway.
@Faff, thanks for the alternative ;) I might use that in future, it seems a lot easier.


@Flipe, thanks a lot, it worked perfectly ^_^ You're fantastic!
Topic archived. No new replies allowed.