do while

Definition

The do while statement is used to create a loop. It is similar to the while loop except that the test condition is evaluated at the end of the loop. Therefore, a do while loop will always execute at least once.

Syntax

do while

A simple do while statement has the following syntax:

do {
    block;
} while ( condition );
do {
    block;
} while ( condition );

JavaScript and Java syntax.

Examples

Example 1: Quiz Question

For this example we will check if a user understands a concept. We can prompt the user for an answer at least once and keep prompting until the user enters the correct answer. The do while loop can be used to achieve this.

  1. The do while loop will ask the user to enter an answer (a, b or c) and check if the answer is correct (b). If the answer is not correct, the program loop will repeat and the user will be asked for an answer.

    However, the code does not recognise an upper case character 'B' as correct.
  2. var answer; 
    do {
        answer = prompt("Loops at least once:  a) while, b) do while, c) for","");
    } while ( answer != 'b' );     
    
    alert("Correct! The do while loops at least once.");
    Scanner input = new Scanner(System.in);
      
    char answer;  
    do {
        System.out.println("Loops at least once:  a) while, b) do while, c) for");
        System.out.println("Enter a, b or c");
        answer = input.next().charAt(0); 
    } while (answer != 'b');  
    
    System.out.println("Correct! The do while loops at least once.");  
  1. We now ensure the program is able to deal with both upper case and lower case input. The input value is converted to lower case prior to testing and will accept both 'b' and 'B' input as the correct answer.
  2. var answer; 
    do {
        answer = prompt("Loops at least once:  a) while, b) do while, c) for"," ");
        answer = answer.toLowerCase();   
    } while ( answer != 'b' );      
    
    alert("Correct! The do while loops at least once.");
    Scanner input = new Scanner(System.in);
      
    char answer;  
    do {
        System.out.println("Loops at least once:  a) while, b) do while, c) for");
        System.out.println("Enter a, b or c");
        answer = input.next().charAt(0); 
        answer = Character.toLowerCase(answer);
    } while (answer != 'b');  
    
    System.out.println("Correct! The do while loops at least once."); 
To get a good understanding of the logic developed view Example 1 in the Code Visualiser

Example 2: Guess a Secret Number

In this second example we will use the do while loop to create a simple game that prompts a user to guess a secret number between 1 and 15. The user enters guesses until their input matches the secret number.

  1. We create a variable secretNumber and give it the integer value 10. A variable userGuess is used to store the guess entered by the user and variable guesses will be used to track how many guesses the user takes.

    Each time through the loop we get the next guess from the user and we update the number of guesses by one. We will repeat the loop block until the number provided by user matches the value stored in secretNumber.

    When the number is guessed we will exit the loop and let the user know how many guesses they took to find the secret number.
  2. var secretNumber = 10;
    var guesses = 0; 
    var userGuess;
    
    do {
        userGuess = prompt("Enter a number between 1 and 15","");
        userGuess = parseInt(userGuess);
        guesses++;  
    } while (userGuess != secretNumber);
    
    alert("Guessed in " + guesses + " attempt(s).");
    Scanner input = new Scanner(System.in);
      
    int secretNumber = 10;
    int guesses = 0; 
    int userGuess;
    
    System.out.println("Guess the Number Game");
    
    do {
        System.out.println("Enter a number between 1 and 15");
        userGuess  = input.nextInt();   
        guesses++; 
    } while (userGuess != secretNumber);
    
    System.out.println("Guessed in " + guesses + " attempt(s).");
  1. Now we will extend the program to give the a hint (higher or lower) based on the users last input.

    We create an empty string variable hint which is updated within the loop with an appropriate message only if the users guess is higher or lower than the secret number. The value in this variable is concatenated (joined) to the message displayed when the user is asked for a guess.
  2. var secretNumber = 10;
    var guesses = 0; 
    var hint = ''; 
    var userGuess;	  
    	  
    do {
        userGuess = prompt("Enter a number between 1 and 15" + hint," ");
        userGuess = parseInt(userGuess);
        guesses++;  
        if (userGuess > secretNumber) {
            hint = ' (HINT: less than ' + userGuess + ')';
        } else if (userGuess < secretNumber) {
            hint = ' (HINT: greater than ' + userGuess + ')';
        }
    } while (userGuess != secretNumber);
    
    alert("Guessed in " + guesses + " attempt(s).");
    Scanner input = new Scanner(System.in);
      
    int secretNumber = 10;
    int guesses = 0; s
    int userGuess;
    String hint = ""; 
    	  
    System.out.println("Guess the Number Game"); 
    do {
        System.out.println("Enter a number between 1 and 15" + hint + "");
    	userGuess  = input.nextInt();   
        guesses++;  
        if (userGuess > secretNumber) {
            hint = " (HINT: less than " + userGuess + ")";
        } else if (userGuess < secretNumber) {
            hint = " (HINT: greater than " + userGuess + ")";
        }
    } while (userGuess != secretNumber);
    
    System.out.println("Guessed in " + guesses + " attempt(s).");
You can view Example 2 in the Code Visualiser