42.6k views
5 votes
Class Main {

static void printPowers(int howMany, int nrRows) {

int n=1;

while(n<=nrRows) {

int power = 1;

while(power <= howMany) {

System.out.printf("%d ", (int) Math.pow(n,power));

power++;

}

System.out.println();

n++;

}

}



public static void main(String[] args) {

printPowers(3,5);

}

}
1. Rewrite your method printPowers from 7B to use a for loop instead of a while loop.

2. Rewrite your method printPowers from 7B to use a do-while loop instead of a while loop.

1 Answer

4 votes

Answer:

class Main {

static void printPowers(int howMany, int nrRows) {

for(int n=1; n<=nrRows; n++) {

for(int power = 1; power<=howMany; power++) {

System.out.printf("%d ", (int) Math.pow(n, power));

}

System.out.println();

}

}

public static void main(String[] args) {

printPowers(3, 5);

}

}

class Main {

static void printPowers(int howMany, int nrRows) {

int n = 1;

do {

int power = 1;

do {

System.out.printf("%d ", (int) Math.pow(n, power));

power++;

} while (power <= howMany);

System.out.println();

n++;

} while (n <= nrRows);

}

public static void main(String[] args) {

printPowers(3, 5);

}

}

Step-by-step explanation:

The for loop gives the cleanest, shortest code.

User Qoomon
by
7.8k points

Related questions

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.