CS 1102 Discussion Forum Unit 2
CS 1102 Discussion Forum Unit 2
int count = 5;
count --;
int count = 5;
do{
count --;
int a = 5;
int b = -1;
do {
b ++;
while (b<a);
int a = 5;
int b = -1;
while (b<a){
b ++;
int a = 5;
3. An example of for loop along with the equivalent while loop and do-while loop.
System.out.println(count);
System.out.println(count);
count --;
System.out.println(count);
count --;
While loop is used in situations where we need to repeat the code for unknown number of
times. It will repeat as many times as its condition remains true. First, while loop will check the
Boolean expression and if its true, then it will execute the code within the loop and then go back
to the start. Only when the Boolean expression is true, it will exit the loop. While loop is easy to
read but it is slow and can cause infinite loop if not properly coded.
Do-while loop is used in situations where we want the code to execute at least once.
The flow of do-while loop is a little bit different from while loop. Unlike while loop, which
executes only after checking its condition, do-while loop will execute at first then check the
condition second. Therefore, the code is executed at least one time. Do-while loop is less
readable than while loop but it is the fastest one of the three loops.
For loop is used in situations where we want the code to execute for a limited number of
times. In the case of for loop, it is easier to read and less possible to accidently stuck in an
infinite loop. It is also the second fastest loop. While loop and for loop can end without any
Reference:
Eck, D. J. (2019). Introduction to programming using Java, version 8.1. Hobart and William