Loops — While Loop

Loops

As the name suggests, loops in programming are used when we are supposed to repeat the same instruction specific number of times. In situations like these, we put the instructions to be repeated inside the body of the loop and then specify other elements in the loop structure.

There are three types of loop structures that are used in C language:

  1. For loop.
  2. While loop.
  3. Do – While loop.

While Loop

In the while loop, the statements in the loop body are repeated until the condition becomes false.

While loop is preferred in cases where the number of iterations is not known beforehand.

Syntax:

 while (condition)

{

Statement(s)

}

How it works:

As the program encounters the keyword “while”, it first evaluates the condition inside the round brackets, if the condition turns out to be true, only then the loop body is executed, after executing the loop body the program again go back to the condition and evaluate it. The loop body keeps on executing until the condition turns out to be false.

If the condition evaluates as the false very first time, then the loop body will not be executed and the program will skip the statements inside the loop body and directly jump to the statements following the loop body.

Flow Chart:

Example code:

Program to print backward counting starting from any number that the user enters.

 Output:


The “Condition”:

The condition, in the round brackets after the keyword while, can be any expression also. As long as the expression evaluates a non-zero number, it will be considered true. And as the expression evaluate zero (0), it will be assumed as false and the loop will stop.

Also, you can write a single variable in place of condition, it was also be considered true until the variable contains a non-zero number. As soon the value of the variable changes to zero (0), it will be assumed as false and the loop will stop.

The example code’s condition can also be written as:

while (i)

This simple statement is the replacement of, while (i<=0)

Loop Counter:

The loop counter can be incremented or decremented as per the requirement. It is not necessary that the loop counter variable can only be an integer type. You can also make a float type looping variable if required.

Single statement for increment/decrement and condition:

If you don’t like to write long code, you can also gain the same functionality in the lesser line of codes, if you code smartly. Let me show you how:

while (++ i <=10)

In this statement first the value of the variable “i” is incremented and then it is checked according to the given criteria.

However, if you will write the statement like;

while (i++ <=10)

In this case, the condition will be checked first and then the looping variable will be incremented.

while (i– <=0) –>  we can use this statement in the example code and then skip the decrementing statement from the loop body.