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
- The condition is an expression that is evaluated at the start of each pass through the loop, and which evaluates to either
true
orfalse
. - The loop will stop executing when the condition becomes
false
. - The block is a block of code that gets executed while the condition evaluates to
true
.
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.
- We'll use a
while
loop and a variabletimesLine
will act as our counter. We want to go through the loop 12 times, so we will initialisetimesLine
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!
Python Note: Short cut for adding one to a variable,
i++
, not used in Python.Warning: Since the loop condition isi <= 12
we need to ensure that thei
variable gets updated within the loop. Otherwise, it will always evaluate totrue
and will loop forever (an infinite loop)!
- 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++; }
JavaScript Note: As in this example, the mark is entered in a text field, the data type will be a string. However, we want to convert it to a number (integer) using theparseInt()
function.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
Python Note: Method input() produces string values so we convert to an integer with the int() method.
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.
- 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;
Java Note: Java requires that the variable type is defined before use.marksEntered = 0 sumMarksEntered = 0
- 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) + ': ' )
Python Note: As we cannot concatenate strings and integers in Python we convertmarksEntered
to a string with thestr()
method.Warning: Since the conditions ismarksEntered < 6
and themarksEntered
variable never gets updated with the code written so far, if the conditionmarksEntered < 6
evaluates totrue
, it will loop forever! This is called an infinite loop. Infinite loops are bad! They will most likely crash your browser! We must therefore fix this straightaway by updating the value ofmarksEntered
each time the user enters a new mark.
- JavScript and Java - We will increment the value of the variable inside the loop using
marksEntered++;
, which is equivalent tomarksEntered = marksEntered + 1;
- Python does not use
++
(e.g., marksEntered++) so we will usemarksEntered += 1
(again this is equivalent tomarksEntered = marksEntered + 1;
).
- JavScript and Java - We will increment the value of the variable inside the loop using
- Each time the user enters a new mark, this should be added to the
sumMarksEntered
variable. We'll use an intermediate variablemoduleMark
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++; }
JavaScript Note: As in this example, the moduleMark is entered in a text field, the data type will be a string. However, we want to convert it to a number (integer) using theparseInt()
function.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
Python Note: Methodinput()
produces string values so we convertmoduleMark
with theint()
method.Notice how the conditionmarksEntered < 6
will betrue
initially as the variable is initialised to 0. Inside the loop, this variable is incremented (one is added to its value). This means that the value of this variable is going to get bigger and bigger, until we reach the value 6, which is defined by the condition statement. This also ensures that we do not have an infinite loop. Once we reach the value 6, the condition for thewhile
loop becomesfalse
and the loop doesn't get executed again. Instead, the code that comes after the loop is.
- 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 theyearAverage
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 );
Java Note: 6.0 (sumMarksEntered / 6.0) required to force the result into a doublemarksEntered = 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.