Coupon Accepted Successfully!


The while Loop

Another kind of loop structure in C/C++ is the while loop. Its format is as given in Figure.


The while loop


The test condition may be any expression. The loop statements will be executed till the condition is true, i.e. the test condition is evaluated and if the condition is true, then the body of the loop is executed. When the condition becomes false the execution will be out of the loop.

The execution of the while loop can be followed by Figure.

Flow chart for while-loop


Here, the block of the loop may either contain single statement or a number of statements. The same block can be repeated. The braces are needed only if the body of the loop contains more than one statement. However, it is a good practice to use braces even if the body of the loop contains only one statement.

Steps of while loop are as follows.

  1. The test condition is evaluated, and if it is true, the body of the loop is executed.
  2. On execution of the body, and updating the variable test condition is repeatedly checked. If it is true the body is executed.
  3. In case the test condition fails the control transfer out of the loop or stop.

Given below are a few example problems on while loop.

6.6 Write a program to add 10 consecutive numbers starting from 1. Use the while loop.

Explanation: In the above program integer variable ‘a’ is initialized to 1 and variable ‘sum’ to 0. The while loop checks the condition for a<=10. The variable ‘a’ is added to variable ‘sum’ and each time ‘a’ is incremented by 1. In each while loop ‘a’ is incremented and added to ‘sum’. When the value of ‘a’ reaches 11, the condition given in while loop becomes false. At last the loop is terminated. The sum of the number is displayed.

6.7 Write a program to calculate the sum of the individual digits of an entered number.


Explanation: The logic behind the program is to extract each time the LSD(lower significant digit). Each time divide the number by 10 so as to shift it by one place ). To extract the LSD we use the fact that num % 10 = the remainder on dividing num by 10.

6.8 Write a program to check whether the entered number is a palindrome or not.

Explanation: Palindrome number is a number that is equal to its reverse (e.g. 51715). The above program first reverses the number and stores it in ‘b’. Then it compares ‘b’ with original number to tell you whether or not the number is a palindrome. See that in each iteration the LSD of ‘a’ is being made MSD of ‘b’.’The ‘a’ is being shifted left and ‘b’ is shifted right by one digits in every iteration. Iterations are being done until ‘a’ exhausts or becomes equal to 0.

Test Your Skills Now!
Take a Quiz now
Reviewer Name