function that returns 2 raised to the power of its argument

Hi, Im new to the forums, and very new to C++. I have an assignment for my entry level c++ class that I am having trouble with. What I have to do is written in the title. This is what I have, let me know if you would change anything or if this would even work. The argument must be greater than or equal to zero.


int power (int two, int exponent)
{
int zero = 1;

if (exponent == 1)
return base;

else if (exponent == 0)
return zero;

else

return two * power(two, exponent - 1);
}
int power (int two, int exponent)
{
int zero = 1;
int two = 2;

if (exponent == 1)
return two;

else if (exponent == 0)
return zero;

else
return two * power(two, exponent - 1);
}
Don't make magic numbers. Use the number itself.
1
2
3
4
5
6
7
8
9
10
int two_to_the_power_of( int exponent )
{
  if (exponent == 0)
    return 1;

  if (exponent == 1)
    return 2;

  return 2 * two_to_the_power_of( exponent - 1 );
}

The best way to know if it works is to test it.
1
2
3
4
5
6
7
8
9
10
#include <iostream>

...

int main()
{
  for (int n = 0; n < 10; n++)
    cout << "2 to the " << n << " is " << two_to_the_power_of( n ) << endl;
  return 0;
}

By the way, what happens if the user says two_to_the_power_of( -3 );?

Hope this helps.
I like how 'two' contains 2, but 'zero' contains 1.
Allow me to comment on the code that you have so far:
1
2
3
4
5
6
int power (int two, int exponent)
{
int zero = 1;
int two = 2;

//...
<- The parameter 'two' is either not necessary or named very, very poorly.

<- This is humorous, at least.
<- This local variable 'two' hides the function parameter 'two'. 

   The rest of the logic just reads silly because of the variable names.  :P
Last edited on
closed account (jLNv0pDG)
@Duoas: I know it's a different way of doing the same thing, but aren't for loops more efficient than recursive function calls?

1
2
3
4
5
6
7
8
9
int two_to_the_power_of( int exponent )
{
	int answer = 1;

	for (int i = 0; i < exponent; ++i) 
		answer *= 2;
		
	return answer;
}
Thanks alot for the feedback guys, sorry I know I'm not very good at writing code but you have to start somewhere!
Anybody have any opinion on a good strategy to learning C++??? Any good books??? How did you guys do it?
@farcear
Yes, they are, but I only made two changes to the OP's code, which was recursive.

@kyleg033
Just do it, and learn everything you can about what it is you are currently doing.

I started out writing simple utilities (menu systems and the like) and games (breakout clone, hangman, Ladder clone, etc) and utilities to help (pixel editor, dungeon map editor, etc).
Duoas,

Thanks alot you are a huge help!
Short and sweet (or perhaps not so sweet, but definitely short)

1
2
3
int two_pow(int exp){
	return 1 << exp;
}
Shhh! That's how I would have done it.
Topic archived. No new replies allowed.