ana
ana

Reputation: 97

Converting a for loop into a while loop (java)

I need to convert a for-loop into a while-loop.

Here is the for-loop:

double price;
for (int person = 1; person <= 20; person++){
     for (int day = 1; day <= 10; day++){
          price = 2.5;
          price = price * person * day;
          System.out.print("\t" + price);
     }
     System.out.println();
}

Here is what I tried:

double price = 2.5;
int person = 1;
while (person <= 20){
      int day = 1;
      while (day <= 10) {
           price *= person * day;
           System.out.print("\t" + price);
           day++;
      }
      System.out.println();
      person++;
}

However, I do not get the same output. Could someone help me with this code?

Upvotes: 2

Views: 91

Answers (1)

Andronicus
Andronicus

Reputation: 26046

Once you've got price inside a nested loop and the second time - outside. The equivalent would be:

int person = 1;
while (person <= 20){
      int day = 1;
      while (day <= 10) {
           double price = 2.5;
           price *= person * day;
           System.out.print("\t" + price);
           day++;
      }
      System.out.println();
      person++;
}

P.S.: Introducing a variable on every loop turn does not make much sense, why not inlining it: System.out.print("\t" + (2.5 * person * day));?

Upvotes: 2

Related Questions