# Beginner problem- Integer based exponentiation

• March 6th, 2014, 10:52 AM
wolfyt
Beginner problem- Integer based exponentiation
Hello everyone,

I have an assignment to basically recreate what Math.pow does but with integers through the use of a while or for loop.

My code when run multiplies and then saves the number. (I.E. 2^2=4, but 2^3= 2*2=4 and 4 would get saved so the last calculation would be 4*4=16).

The following is the code I believe the problem is in the while loop, as I don't know how to make it so it doesn't save the problem of the first calculation:

Code Java:

```  import java.util.*; public class IntPower { public static void main(String[] args) { int base=0; int power=0; int result=0; base=IntegerPower(base, power, result); System.out.println("The result of the calculation is: "+base); } public static int IntegerPower(int base, int power, int result) { Scanner input = new Scanner(System.in); System.out.println("Enter the base: "); base=input.nextInt(); System.out.println("Enter the exponent: "); power=input.nextInt(); int count=1; while(count<power) { base*=base; count++; }   return base; } }```
• March 6th, 2014, 10:58 AM
Norm
Re: Beginner problem- Integer based exponentiation
why are parameters passed to the method? Their values are immediately changed by the method.
The prompts for the input values for the method should be done OUTSIDE of the method and passed to the method as args.

Get the values for the method before calling the method.
Pass the values as args to the method which then uses them to compute the result and return it.

The code should build the result in a new variable and save the value of base for each iteration.
• March 6th, 2014, 06:50 PM
dicdic
Re: Beginner problem- Integer based exponentiation
Quote:

public static int IntegerPower(int base, int power, int result)
all you need in Exponential operations are base and exponent, why do you also have the result in your parameter?

Quote:

My code when run multiplies and then saves the number. (I.E. 2^2=4, but 2^3= 2*2=4 and 4 would get saved so the last calculation would be 4*4=16).
your solution is wrong
because you mean that 2^3 = 16?
actually 2^3 is 8 not 16
how?
base = 2
exponent = 3
multiply the base by itself 3 times:
base * base * base = answer
2 * 2 * 2 = 8

another example 2^4 = 16 how:
base = 2
exponent = 4
multiply the base by itself 4 times
base * base * base * base = answer
2 * 2 * 2 * 2 = 16

you can use scientific calculator for verification.

Quote:

The following is the code I believe the problem is in the while loop, as I don't know how to make it so it doesn't save the problem of the first calculation:
the problem is your solution as what I told above:
Code java:

``` while(count<power) { base*=base; count++; }```