Need help with void recursive problem, 1,2,3,..n

Hi, I was really struggling with the following problem for an assignment. I really confused on how exactly I should use the void recursive function for it. I have spent almost 2 hours figuring out solutions but can't find one. I have wrote what I currently have, i no it might not make be really wrong. Any help is appreciated. Thanks.

Submit a complete program that has a recursive void function that takes a
single int argument n and writes the integers 1, 2, …, n on the screen.

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


int main()
{
	int n;
	cin >> n;
	writeUntilN(n);
	return 0;
}

void writeUntilN(int n)		
{
	if (n = 1)
	{
		cout << n;	
	}
	else
	{
		writeUntilN((n++));
		cout << n;
	}
Either this:

else
{
writeUntilN(n-1);

.. or you need the function writeUntilN to have 2 parameters
Thanks so much! It actually works. But, do you mind explaining how it works especially the recursive part as i don't really understand this code, since i just looked at a bunch of examples and randomly wrote it. Thanks.
Explanation:
In line 21 writeuntillN will be called BEFORE n is written out. That means that the resursion will calculate all values of n on stack before any output begins. The output will start from the deepest function call, where n=1, and it will then unwind untill the first function call where n will be the greatest, which will output the greatest value of n, just before the recursion exits.

In order to comprehend this recursion better, I recommend you to use a debugger. Use "step-into" to go through the writeUntillN function.

The best debugger is available in Visual Studio (free) but the debugger GUI in Code::Blocks is also OK.
Last edited on
so what u mean is that lets say n =5 when inputed, so it will skip the first step and will go to the else statement where it will continue to add 1 to 1 until it reaches 5 and then it will continue and output those values, 1,2,3,4,5?

Also, is there anyway I can get, ex. "1, 2, 3, 4, 5" when inserting ", " after the n's in the code cause whenever i add them, i get "1, 2, 3, 4, 5," with the comma after 5 but i don't want that comma at the end. Thanks.
"where it will continue to add 1 to 1 until it reaches 5 and then"

No, n is 5 at the beginning, so it will produce new values of n in the order: 5,4,3,2,1

Judging from your second question, I would say that it's too early for you to grasp recursion, so perhaps it would be better to just concentrate on something else.
closed account (D80DSL3A)
You could use a local static int to keep track of recursion depth. Increment it before the recursive call and decrement after. Print a comma only when recursion depth is positive. eg:

1
2
3
4
5
6
7
8
static int recDepth = 0;// initialized on 1st function call
...
++recDepth;
writeUntilN(n-1);
--recDepth;
cout << n;
if(recDepth > 0)
    cout << ',';
Last edited on
I dont think u understood what i meant with the comma at the end. Please try to run the following code and u will see that it produces, "1, 2, 3, 4, 5,", but i dont want that extra comma after 5. As for learning recursion, we just learned it last week for my intro to programming class, it was the last topic covered in the course.

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

void writeUntilN(int);

int main()
{
	int n;
	cout << "Please enter an integer:";
	cin >> n;
	writeUntilN(n);
	return 0;
}

void writeUntilN(int n)		
{
	if (n == 1)
	{
		cout << n << ", ";	
	}
	else
	{
		writeUntilN((n-1));
		cout << n << ", ";
	}
}
Last edited on
Thanks fun2code, the local static worked, but would i include it before the function definitions, like after the #include<iostream, etc. before the int main().

Also, i just wanted to confirm with u guys if this is how it works:
if for ex. the user enters 5,

it goes to else, and does (5-1) which gives 4 and this work is checked in the if but if it fails it goes again to the recursive part and does (4-1) giving 3 and the process repeats until after (2-1) which results in 1 and ends up being true for the if statement outputting "1, " and after it begins to follow the stack (last in/first out) process and just outputs, 2, 3, 4, and then outputs the last number n, 5. I'm not sure if the way I explained it makes sense but i want to no if this is how it works. Thanks.
closed account (D80DSL3A)
I declared it within the function.
Your code probably satisfies the assignment requirement, so it shouldn't hurt to share my code.
You can run it in the shell here to see it work. Click the wheel thingy in the upper right corner of the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

void f(int n)
{
    static int recDepth = 0;

    if( n == 0 ) return;// last recursion just returns

    ++recDepth;
    f(n-1);
    --recDepth;
    std::cout << n;
    if( recDepth > 0 )
        std::cout << ',';//  print comma
    else
        std::cout << '\n';// last thing printed is a newline
}

int main()
{
    f(5);
    f(8);

    return 0;
}
Is the way I did declaring it as a global ok or is that not good, it works but i want to know if it is normal to do it like this.

Also, could read my explanation of how i think the recursion in the code works and tell me if its right:

if for ex. the user enters 5,

it goes to else, and does (5-1) which gives 4 and this work is checked in the if but if it fails it goes again to the recursive part and does (4-1) giving 3 and the process repeats until after (2-1) which results in 1 and ends up being true for the if statement outputting "1, " and after it begins to follow the stack (last in/first out) process and just outputs, 2, 3, 4, and then outputs the last number n, 5. I'm not sure if the way I explained it makes sense but i want to no if this is how it works. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

void writeUntilN(int);

static int recDepth = 0;			//initialized on 1st function call

int main()
{
	//static int recDepth = 0;
	int n;
	cout << "Please enter an integer:";
	cin >> n;
	writeUntilN(n);
	return 0;
}

void writeUntilN(int n)		
{
	if (n == 1)
	{
		cout << n << ", ";	
	}
	else
	{
		++recDepth;
		writeUntilN((n-1));
		--recDepth;
		cout << n;
		if (recDepth > 0)
		cout << ", ";
	}
}
closed account (D80DSL3A)
Your explanation seems pretty good. When the calls are returning, as the call stack is unwinding, execution resumes just after the function call, line 28 in your code.

Declaring recDepth at global scope works, as you've noted. When it's declared globally it doesn't need to be static though. If you remove the keyword static from line 6 it will still work.
Many prefer to declare variables within the scope where they're used. recDepth is used only in the writeUntilN function which is why I declared it there. The static type makes it a single variable which persists across function calls. It is assigned = 0 only the first time the function is called.
If you declared it non-static as int recDepth = 0; in the function then it would be a regular local variable and be set=0 in each function call. This method wouldn't work for us.
Topic archived. No new replies allowed.