0

What are the differences between a while loop and a do-while loop? Convert the following while loop into a do-while loop.

int sum= 0; int number = input.nextInt(): while (number !=0) { sum += number; number = input.nextInt();

20th Nov 2020, 5:35 PM
Zaina Fannana
2 Answers
+ 1
The differences is do while loop execute code block before checking the condition, while loop is vice versa
20th Nov 2020, 6:21 PM
Toan Phan
0
To add on to what @DungNgoc said, you use a do while look if you want something to be executed in a while loop at least once, since it runs before checking condition, but a while loop on the other hand must check the condition first and may never run at all. here is the program using a do-while loop: https://code.sololearn.com/ct86x3o9bfuQ/#java You may not have noticed but converting the program to a do while loop will actually be inefficient because lets say the user does input a zero on the first time, instead of the program ending it will do what's in the do while loop and ask for another input, hence it goes against the complete purpose of the code. Make sure you use the appropriate loops for your programs, some loops just make more sense than others in certain scenarios. Anyways, happy coding!
21st Nov 2020, 1:14 AM
pNK
pNK - avatar