Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: How do I calculate power using for loop?

1. ## How do I calculate power using for loop?

Hello I need some help.

How do I use for loop in order to calculate the power of a number?

In here, I used Math.pow and I need to change it and use for loop instead.

```import java.util.Scanner;

public class LoopActivity
{
public static void main(String[] args) {

/*------------------------------------------*/
Scanner scanner = new Scanner(System.in);
int loopRange = 0, sumOdd = 0, sumEven = 0, n1 = 1, n2 = 2, x1 = 1;
/*------------------------------------------*/

//if loopRange is less than 0 the loop doesn't work.
do {
loopRange = scanner.nextInt();
if(loopRange < 0) {
System.out.println("\nError: Invalid loop range.\n\tPlease enter a number equal or grater than 0.\n");
}
} while(loopRange < 0);

for(int x2 = loopRange/2 ; n1 <= loopRange ; x2--, x1++) {
//odd
int ans1 = (int) Math.pow(n1, x1);
System.out.println(n1 + "^" + x1 + "=" + ans1);
sumOdd += ans1;
n1 += 2;

//even
if(n2 <= loopRange) {
int ans2 = (int) Math.pow(n2, x2);
System.out.println(n2 + "^" + x2 + "=" + ans2);
sumEven += ans2;
n2 += 2;
}
}

System.out.println("The sum of ODD increasing power is: " + sumOdd);
System.out.println("The sum of EVEN decreasing power is: " + sumEven);
}
}```

2. ## Re: How do I calculate power using for loop?

int ans2 = n2^x2;
if you want to use for loop:
```    public static double power(int base, int exponent) {
double b = base;
if(exponent <= 1) {
for(int e = exponent; e < 1; e++) {
b /= base;
}
} else {
for(int e = 1; e < exponent; e++) {
b *= base;
}
}
return b;
}```
it works only with integer exponent