Search code examples
javafor-looppow

Java for loop I want to print the result the same way that i print the numbers that i use


I want to print the result the same way that i print the numbers that i use. for ex i print 1,2,3,4 2,3,4,5 but the pow remains the same 1024,1024,1024,1024.

public static void main(String[] args) {
    int d = 0, e = 0;
    double c = 0;
    for (int a = 1; a < 5; a++) {
        d = a;
        for (int b = 2; b < 6; b++) {
            c = java.lang.Math.pow(a, b);
        }
    }
    for (int a = 1, b = 2; a < 5; a++, b++) {
        d = a;
        e = b;
        System.out.println(d + " " + e + " " + c);
    }
}

Solution

  • This should work, and is also more readable.(you really ought to indent code properly). Your problem is in the loop logic. What you are doing is probably possible with for loops, but i think a while loop with two conditionals would work nice.

    int a = 1;
    int b = 2;
    double c = 0.0;
    
    while (a < 5 && b < 6){
      c=java.lang.Math.pow (a,b);
      System.out.println ( a+ " " +b +" " + c); 
      b++;
      a++;
    }