Search code examples
loopsfor-loopintegerexponent

How to use exponents using a for loop


I am working on a functions HW for my programming class and Im trying to write a function that will allow me to do exponent math (in a simple form). (Oh and I can't use the actual exponent function, I have to write my own function using for loops, if statements or other things like that.) EX: user enters base and then enters the power to raise it by. So the user enters: 5 3 it should be 5 to the 3rd power, so it should output 125 (5x5x5). However my for loop is not working properly. How should I structure my for loop to properly handle exponent math? code: int main(){

int base, pow;

scanf("%d", &base);
scanf("%d", &pow);

int i;
for (i=0; i<=pow; i++) {
    i *= base;
    printf("%d\n", i);
}

printf("%d", i);

Solution

  • Well you're using the same variable for the loop and the result. You don't want to do that.

    int j = 1;
    for(i =  0; i < pow; i++)
    {
          j*= base;
    }
    

    Is what you want. You're also off by one on the loop count. With i <= pow you have

    i=0, j * 5 = 5, i=1

    i=1, j * 5 = 25,i=2

    i=2, j * 5 = 125,i=3. This is where you want to stop but 3 <= 3 so it goes again.

    i=3, j *5 = 625,i=4. 4 is not <= 3 so it will then stop here.