Writing a function that returns a base and an exponent (Details in post)

Hey there guys. I recently bought the C++ How to Program, Early Objects Version 9th edition to better verse myself in C++ programming. I am on chapter 6 of the book and I am in the questions section and I am having trouble with this question.

Write a single function integerPower(base, exponent) that returns the value of base^exponent

For example, integerPower(3, 4) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero, integer, and that base is an integer. DO NOT USE ANY MATH LIBRARY FUNCTIONS

I felt the need to put that in all caps and bold because they don't want me to use #include cmath. I could easily do this if I could use pow(x, y) but I cannot. This question has got me stumped. I will post the code I have so far! Maybe I am just not understanding the question properly. Any help would be very much appreciated. Thanks guys

Edit: I know what I have in the function is wrong, but I was just trying things out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  int integerPower(int base, int exponent)
{
	int answer = base * exponent;
	return answer;
}

int main()
{
	cout << integerPower(3, 4);



	return 0;
}
Last edited on
To find x to the power of y, you need to multiply x by x y times.
Use loop for that
@MiiNiPaa Could you explain a bit more? If I were to use a loop how exactly would I go about it? I assume it would be a for loop, but I am not sure what exactly I would do.
Last edited on
well, it would be loop repeating y times, which will multiply result by x each iteration.
To raise a base to a power (let's call it n), you must multiply the base by itself n times. So your condition in psuedocode would be "while the base has not been multiplied by itself n times, multiply the previous result by the base again." Try turning that into a loop.
Topic archived. No new replies allowed.