Answer to Question #124547 in Java | JSP | JSF for Lebenis

Question #124547
Give an example of a while loop, then provide the equivalent do-while loop and for loop. Then give a different example of a do-while loop, along with the equivalent while loop and for loop. Finally, give an example of a for loop, along with the equivalent while loop and do-while loop. Use your examples to illustrate the advantages and disadvantages of each looping structure, and describe those advantages and disadvantages. In Java
1
Expert's answer
2020-06-30T07:49:50-0400
// while-loop

class Loop {
    public static void main(String[] args) {
      
        int i = 1;
	   
        while (i <= 10) {
            System.out.println("Line " + i);
            ++i;
        }
    }
}
// do-while-loop

class Loop {
    public static void main(String[] args) {
      
        int i = 1;
	   
     do{
            System.out.println("Line " + i);
            ++i;
        }while (i <= 10);
    }
}
//for-loop

class Loop {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			System.out.println("Line " + i);
		}
	}
}
while (testExpression) {
    // codes inside the body of while loop
}
In the above syntax, the test expression inside parenthesis is a boolean expression. If the test expression is evaluated to true,

statements inside the while loop are executed.
then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false. If the test expression is evaluated to false,

the while loop is terminated.

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked.


Between a WHILE and FOR loop, you can use them interchangeably. To be a purist, you could make your decision base on the nature of the conditions. If you're performing a count-based loop, then a FOR loop would make the most sense.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS