-1

In response to this prompt:

Write a 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 base is an integer. The function integerPower should use for or while to control the calculation. Do not use any math library functions.

I wrote this program:

#include <iostream>
#include <conio.h>
using namespace std;

int integer (int a, int b) {
  int e;

  for (int i = 1; i <= b; i++)
    e *= a;

  return (e);
}

int main () {
  cout << "enter number and exponent";
  cin >> num >> exp;
  cout << num << "to the power" << exp << "is" <<;
  int num, exp, n;
  integer (num, exp, n);
  getch ();
  return 0;
}

For some reason the function integer (int a, int b) returns 0 no matter what the values of a and b are. Why?

The SE I loved is dead
  • 1,517
  • 4
  • 23
  • 27
setup_741
  • 1
  • 1
  • Hint: zero times anything, (except maybe infinity), is still zero! – Martin James Dec 21 '13 at 11:38
  • @Martin zero times infinity is maths undefined behaviour `;-)` – rubenvb Dec 21 '13 at 11:39
  • 1
    ***PLEASE*** do **NOT** use `exp` as a variable name. Especially if you are `abusing namespace std;` (which you shouldn't in fact be using, but anyway.) It's the name of a math library function. –  Dec 21 '13 at 11:45
  • 2
    @H2CO3: hey, the assignment instructions say not to use any math library functions. What better way to avoid that than shadowing their names? ;-) – Steve Jessop Dec 21 '13 at 11:55
  • No one has mentioned that you're calling the function with too many arguments. – chris Dec 21 '13 at 11:58
  • @SteveJessop Fair enough :D –  Dec 21 '13 at 12:29

4 Answers4

3

You should Initialize e to 1.

int e = 1;

Also, you are not declaring the type of num and exp at the correct place.

int main () {
  cout << "enter number and exponent";
  int num, exp;
  cin >> num >> exp;
  cout << num << "to the power" << exp << "is" << integer (num, exp); // remove the third parameter
  getch ();
  return 0;
}
Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46
0

Inside the function integer, initialize e like this :

int e = 1;

Also, move int num, exp, n; before the cin statement.

sgarizvi
  • 16,623
  • 9
  • 64
  • 98
0

As you can read in other answers, you must declare num and exp variables in main function, and initialize e to 1 in function integer. But you don't need to use the namespace std, you simply add std:: to the reference of its members, like std::cin, std::cout and your code will be more clear yet. Cheers!

0

First of all it is not clear why the exponent equal to 0 was excluded as an acceptable value. I would write the function the following way

int integerPower( int base, unsigned int exponent )
{
   int result = 1;

   while ( exponent-- != 0 ) result *= base;

   return ( result );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335