The While Loop

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.

While Loop

while loop2

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.

while loop flow chart

Tips and Traps

The general form of while is as shown below:

v

Buy This C and C++ Course Now – Click here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.