2

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?

1 Answer 1

2

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));?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.