Loops and the Do-While Loop

Premium Content - Free Preview

You've seen for and while loops before, but this node will review when to use each one and discuss a variety of the while loop.

for & while loops review

If you know how many times a loop will run, you usually should use a for-loop, since you can setup the index variable, condition and increment all in the loop header. For example, the loops below will both print the numbers from 1 to 10, but the for loop has clearer code:

While Loop

int index = 1;
while(index <= 10){
  index = index + 1;

For Loop

for(int index = 1; index <= 10; index=index+1){ 

While Loop Needed

In cases that do not depend on a index variable being incremented, you'll need a while loop instead of a for loop. This is often the case when your loop needs to run as long as an external condition is true, such as:

  • while a game character is alive
  • while a key or button is pressed
  • while a user-set variable is an incorrect value.

For example, here's some code for a really simple guessing game. As long as the user does not guess 5 the program will prompt him for another number. Since it will loop until that number is guessed, it needs a while loop:

public static void guessGame()
    System.out.println("Welcome to the guessing game.");
    System.out.println("Guess a Number");
    int num = getInput(); //a method which gets user's number input
    while(num != 5){
       System.out.println("Guess A Number");
       num = getInput();
    System.out.println("5 is Correct!");

The above code is pretty simple, so click on the "Menu Example" button below for a similar but larger example. The challenge on the bottom will be to improve some similar code.

Menu Example

End of Free Content Preview. Please Sign in or Sign up to buy premium content.


  • Is the Raw I/O correct? If i test the code without changing it to a do...while loop, i get the same incorrect result for each input as after changing it to a do...while loop. I tested input and first is 0, second is 2, third is 4, other is 3, 5, 1.

  • @Peter, The Raw I/O currently just shows some of the input and correct output. Do you want it to show your actual raw output?

  • After each "selection = getInput()" i inserted "System.out.print(selection)" to see the value of selection and it's different from the input in the results. For the other input i was able to

  • i ad my code link, so you will have the right solution...

    my code

Contact Us
Sign in or email us at [email protected]