Can I do the same without the recursion?

Hi There
My name is Lyle and i'm new to programming.

I've noticed something in this code:

// recursive function
#include <iostream>
using namespace std;

void myFunction( int counter)
{
if(counter == 1)

return;

else
{
cout <<counter<<endl;
myFunction(--counter);
return;
}
}

int main()
{
myFunction(10);

cin.get();
return 0;
}

The thing that I've noticed is that the actual task was
to decrement counter if it's greater than 1. So I would
like to know if I could go about it without a recursive function,
like this code example below:

//without recursive function
#include <iostream>
using namespace std;

void myFunction( int counter)

{
if(counter == 1)
return;

else
{
cout <<counter<<endl;
cout << --counter;
return;
}
}

int main()
{
myFunction(10);

cin.get();
return 0;
}




but I don't get the same result,
it just decrements until 9 which is not according to my condition.
I would like to know why and were my mistake is.



Thank you
Lyleo
Recursion can be seen as a LOOP of function calls. It's sometimes advisable to use recursion above a loop, because of complexity. In your case, a simple for loop will do the trick:

1
2
3
4
5
void myFunction(int x)
for(;x != 0; x--)
{
    cout << x << endl;
}


Your code, does the following:
1
2
3
4
5
6
7
8
9
10
void myFunction(int counter)
{
    if(counter == 1) return; // If the input is 1, end the function
    else // In all other cases:
    {
        cout <<counter<<endl; // Show the input
        cout << --counter; // Show the input-1
        return; // End the function
    }
}

This means it will only ever show two values.
Here are both ways:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void countBack(int num) {
	if(num) {
		cout << num << endl;
		countBack(num-1);
	}
}

int main() {
	//Without recursion:
	for(int top=10; top; --top) {
		cout << top << endl;
	}

	//With recursion:
	countBack(10);
	return 0;
}


Note that you can use the number itself as an expression. That's because your set of actions execute only if expression is any value different than 0.
Topic archived. No new replies allowed.