The While Loop
It is often the case in programming that you want to do something a fixed number of times. Perhaps you want calculate gross salaries of ten different persons, or you want to convert temperatures from Centigrade to Fahrenheit for 15 different cities. The while loop is ideally suited for this.
Let us look at a simple example, which uses a while loop. The flowchart shown below would help you to understand the operation of the while loop.
The program executes all statements after the while 3 times. The logic for calculating the simple interest is written within a pair of braces immediately after the while keyword. These statements form what is called the ‘body’ of the while loop. The parentheses after the while contain a condition a condition. So long as this condition remains true all statements within the body of the while loop keep getting executed repeatedly. To begin with, the variable count is initialized to 1 and every time the simple interest logic is executed, the value of count is incremented by one. The variable count is many a time called either a ‘loop counter’ or an ‘index variable’
The operation of the while loop is illustrated in the following figure.
Tips and Traps
The general form of while is as shown below: