Answer to Question #133264 in Java | JSP | JSF for cyril sunday obule

Question #133264
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.
1
Expert's answer
2020-09-15T19:30:13-0400
  //1
    while (true)
      {
    System.out.println ("Hello World");
      }

    for (;;)
      {
    System.out.println ("Hello World");
      }

    do
      {
    System.out.println ("Hello World");
      }
    while (true);

    //2
    boolean flag = false;
    do
      {
    System.out.println ("(Do) You shouldn't be here.");
      }

    while (flag);
    for (; flag;)
      {
    System.out.println ("(For) You shouldn't be here.");
      }


    while (flag)
      {
    System.out.println ("(While) You shouldn't be here.");
      }




    //3
    int[] a = new int[10];
    for (int i = 0; i < a.length; i++)
      {
    a[i] = i;
      }

    int i = 0;
    while (i < a.length)
      {
    a[i] = i++;
      }

    i = 0;
    do
      {
    a[i] = i++;
      }
    while (i < a.length);

The main difference in the operation of loops is the condition check: for 'for' and 'while' the check occurs before the operation is performed, and for 'do while' after (example number 2, the 'for' and 'while' loop will not be executed, unlike ' do while '). Also in 'for' it is convenient to work with indices / counters (example number 3), therefore, it is most often used to work with an array.


for

Advantage:

Convenient work with indices / counters.

Disadvantages:

Not.


while

Advantage:

Not.

Disadvantages:

Not.


do while

Advantage:

Checking the condition after execution.

Disadvantages:

Checking the condition after execution.


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