correct use of recursion?

hello i just made a program that uses recursive functions. but i am not sure if this is really recursion or just something else. (i'm just trying to find out about it myself instead of reading about it). and in my code i am using 2 global variables but they are annoying me. so could anyone tell me how to do it without them ? if that is even possible. i am sorry for looking so newbie :D.

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
#include <iostream>
int count=0;
int solution=1;
int power_of_2(int x);

int main()
{
	int x,answer;
	std::cout<<"2^";
	std::cin>>x;
	answer=power_of_2(x);
	std::cout<<"2^"<<x<<"="<<answer;
	return 0;
}

int power_of_2(int x) {
	if(x>count) {
		solution=solution*2;
		count++;
		power_of_2(x);
	} else {
	return solution;
	}
}
Last edited on
If 1 will be entered the result will be equal to 2. Is it a correct result for 1 in power of 2?
You've got a base case and a repeatable procedure for finding the answer. It's recursion.

@Vlad: Yes...?

To avoid the use of globals you can use the return value of the previous call, and decrement the x before passing it so you can just compare it to zero:
1
2
3
4
5
6
7
int power_of_2(int x) {
	if(x>0) {
		return 2 * power_of_2(x--);
	} else {
	return 1;
	}
}
@Vlad it calculate 2^x not x^2
You've got a base case and a repeatable procedure for finding the answer. It's recursion.

Since i'm new to the concept of recursion i don't know what you mean with the base case and a repeatable procedure.
maybe you could show me where in the code they are?
thanks in advance.
return 2 * power_of_2(x--); that's incorrect.
It may be a conceptual error, as you don't need to modify 'x'.

@OP: read a book.
By the way, your code has undefined behaviour, there are paths without return statement.
@ne555 what's that all about ????
why is it incorrect??
who is OP ?
and i always return since the else?
ne555 is right, my code will give you a stack overflow cause I used post decrement. It should have been return 2*power_of_2(x-1);

The base case is when x == 0, since then the recursion stops.
OP is original poster, ie. you.
The procedure is multiplying the last result by 2.
ok thank you.
Topic archived. No new replies allowed.