sparkles
sparkles

Reputation: 51

exponents without math.pow using for loop (in java)

i need to take 2 inputted numbers and calculate variable 1 to the power of variable 2 is without using math.pow and using a for loop. This is what i have now

    Scanner in = new Scanner(System.in);
System.out.print("Please enter your base: ");
int base = in.nextInt();
System.out.print("Please enter your exponent: ");
int power = in.nextInt();

    int result = mathPower(base, power);
    System.out.println(base + " to the power of " + power  + " is " + result + ".");



}

public static int mathPower(int a, int b) 
{

    int result = a;

    if (b == 0) {

            result = 1;

        }

    if (b < 0) {

           a = (1 / a);
           b = -b;
        }

    for (a = 1; a < b; a++) {

        result = result * a;
        return result;

    }

    return result;
}

}

It only seems to work if the exponent is 0, otherwise it just displays the a value. I need both positive and negative exponents. Thanks in advance!

Upvotes: 0

Views: 12547

Answers (4)

Rakibul Hasan
Rakibul Hasan

Reputation: 61

suppose you have numb1=2 and numb2=6. then

temp=1;   
 if (numb2 < 0) {
       numb1 = 1 / numb1;
       numb2 = -numb2;
    }

    for(int n = 1; n<=numb2; n++){
        temp=temp*numb1;
        }

Upvotes: 1

DCruz22
DCruz22

Reputation: 806

You have three main problems:

  1. The return statement inside the loop is breaking it in the first repetition.

  2. You're using your a variable as the loop variable.

  3. If you allow negative exponents then the return value should be a double.

    public static double mathPower(double a, int b)
    {
        double result = 1.0;

        if (b == 0)
        {
            result = 1.0;
        }

        if (b < 0)
        {
            a = (1.0 / a);
            b = -b;
        }

        for (int i = 0; i < b; i++)
        {
            result = result * a;
        }

        return result;
    }

Upvotes: 2

Frank Puffer
Frank Puffer

Reputation: 8215

The case with b<0 only makes sense with floating point numbers, so I changed the type of a and the return value to double.

public static double mathPower(double a, int b) 
{
    double result = 1;

    if (b < 0) {
       a = 1.0 / a;
       b = -b;
    }

    for (int  i = 0; i < b; i++) {
        result = result * a;
    }

    return result;
}

Upvotes: 2

ZergRushJoe
ZergRushJoe

Reputation: 13

public double power(double base,int pow)
{
    double result = 1;
    if(pow==0)
       return 1;
    if(base == 0)
       return 0;
    if(pow>0)
    {
         for(int i = 0;i<pow;i++)
         { 
              result *= base;
         }
    }
    else
    {
      for(int i = pow;i<0;i++)
         { 
              result *= base;
         }
           result = 1/result;
    }
    return result;
}

Upvotes: -1

Related Questions