while

Definition

The while statement is used to create a loop that executes a block of code as long as (while) the test condition is true. The test condition is evaluted at the start of the loop.

Syntax

while

A simple while statement has the following syntax:

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

Examples

Example 1: Multiplication Tables

Imagine that you want to print out the multiplication table for a given number. E.g., the times table for 6:
    1 times 6 = 6
    2 times 6 = 12
    3 times 6 = 18
    etc.

Let's look at some code to achieve this.

  1. We'll use a while loop and a variable timesLine will act as our counter. We want to go through the loop 12 times, so we will initialise timesLine to 1, and loop while it is less or equal to 12, and increment it by one at the end of each pass through the loop.
    var i = 1;  // Initialise loop counter
      
    // Repeat 1 to 12 times
    while (i <= 12 ) {
        // Do something here
        i++;   // Required to prevent an endless loop!
    }
    int i = 1;  // Initialise loop counter
      
    // Repeat 1 to 12 times
    while (i <= 12 ) {
        // Do something here
        i++;   // Required to prevent an endless loop!
    }
    i = 1  # Initialise loop counter
    
    # Repeat 1 to 12 times
    while i <= 12 :
        # Do something here 
        i = i + 1   # Required to prevent an endless loop!
    
  1. We will get the required number for the multiplication table from the user and store it in the timesTable variable.
    var i = 1;  // Initialise loop counter
      
    var timesTable;   // the times table value chosen
    timesTable = prompt( "Enter the times table required: " );
      
    // Repeat 1 to 12 times
    while ( i <= 12 ) {
        document.write(i + " times " + timesTable + " = " + (i * timesTable) + "<br>");
        i++;
    }
    int i = 1;  // Initialise loop counter
    
    int timesTable;         // the times table value chosen
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the times table required: ");
    timesTable = input.nextInt();
      
    // Repeat 1 to 12 times
    while ( i <= 12 ) {
        System.out.print(i + " times " + timesTable + " = ");
        System.out.println((i * timesTable));  // the answer
        i++;
    }
    i = 1 # Initialise loop counter
    timesTable = int(input( 'Enter the times table required: ' ))
    	  
    while i <= 12 :
        print(i, " times ", timesTable, " = ", i * timesTable)
        i = i + 1 

Example 2: Year Average

Imagine that you want to calculate the year average (in this case, a module is a course component, as university students would know it). The year is composed of 120 credits. For the sake of simplicity, we'll consider that the year is composed of six 20-credit modules.

Let's create the code for this, one step at a time.

  1. Let's create a variable that will hold the number of marks entered: marksEntered and the sum of all the marks entered: sumMarksEntered
    var marksEntered = 0, 
        sumMarksEntered = 0;
    int marksEntered = 0, 
        sumMarksEntered = 0;
    marksEntered = 0
    sumMarksEntered = 0
  1. While the number of marks entered is less than 6, ask for another mark.
    var marksEntered = 0, 
        sumMarksEntered = 0;
          
    while ( marksEntered < 6 ) {
        prompt( "Enter mark for module number " + ( marksEntered + 1 ) + ": ");
    }
    int marksEntered = 0, 
        sumMarksEntered = 0;
          
    while ( marksEntered < 6 ) {
        System.out.println( "Enter mark for module number " + ( marksEntered + 1 ) + ": " );
    }
    marksEntered = 0
    sumMarksEntered = 0
      
    while  marksEntered < 6 :
        input( 'Enter mark for module number ' + str(marksEntered + 1) + ': ' ) 
  1. Each time the user enters a new mark, this should be added to the sumMarksEntered variable. We'll use an intermediate variable moduleMark to store the new mark entered by the user.
    var marksEntered = 0, 
        sumMarksEntered = 0,
        moduleMark= 0;
      
    while ( marksEntered < 6 ) {
        moduleMark= prompt( "Enter mark for module number " + ( marksEntered + 1) + ": " );
        sumMarksEntered = sumMarksEntered + parseInt( moduleMark );
        marksEntered++;
    }
    int marksEntered = 0, 
        sumMarksEntered = 0, moduleMark;
    Scanner sc=new Scanner(System.in);  
      
    while ( marksEntered < 6 ) {
        System.out.print ("Enter mark for module number " +  (marksEntered + 1) + ": ");
        moduleMark= sc.nextInt(); 
        sumMarksEntered = sumMarksEntered + moduleMark;
        marksEntered++;
    }
    marksEntered = 0
    sumMarksEntered = 0
    moduleMark = 0
      
    while  marksEntered < 6 :
        moduleMark= input( 'Enter mark for module number ' + str(marksEntered + 1) + ': ') 	
        sumMarksEntered = sumMarksEntered + int( moduleMark)
        marksEntered += 1
    	
  1. Finally, once the user has entered the 6 marks and we come out of the while loop, we'll calculate the year average by dividing the sum of all the marks entered (sumMarksEntered) by 6. We will use the yearAverage variable for this, and will display the output.
    var marksEntered = 0, 
        sumMarksEntered = 0,
        moduleMark= 0,
        yearAverage = 0;
      
    while ( marksEntered < 6 ) {
        moduleMark= prompt( "Enter mark for module number " + ( marksEntered + 1) + ": " );
        sumMarksEntered = sumMarksEntered + parseInt( moduleMark);	
        marksEntered++;
    }
    yearAverage = sumMarksEntered / 6;
    alert( "Your year average is " + yearAverage );
    
    int marksEntered = 0, sumMarksEntered = 0, moduleMark;
    double yearAverage;
    Scanner sc=new Scanner(System.in);  
      
    while ( marksEntered < 6 ) {
        System.out.print( "Enter mark for module number " + (marksEntered + 1) + ": ");
        moduleMark= sc.nextInt(); 
        sumMarksEntered = sumMarksEntered + moduleMark;
        marksEntered++;
    }
    yearAverage = sumMarksEntered / 6.0;
    System.out.println( "Your year average is " + yearAverage );
      
    marksEntered = 0
    sumMarksEntered = 0
      
    while  marksEntered < 6 :
        moduleMark= input( 'Enter mark for module number ' + str( marksEntered + 1) + ': ')  
        sumMarksEntered = sumMarksEntered + int( moduleMark)
        marksEntered += 1
    yearAverage = sumMarksEntered / 6
    print( 'Your year average is ', yearAverage )


To get a good understanding of the logic developed here and the while loop structure, view this in the Code Visualiser , or play with the code below (press the "Run Code" button to run the code): JS Bin on jsbin.com.