While Loop Statement


Description

While loop statement is used when programmer doesn't knows how many times the code will be executing before starting the loop, as it depends upon the users input.

Syntax

while (test expression is true)
{
statement;
statement;
}

Executes the loop till the test expression condition is true.

Source code

  1. //Using while loop statement
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. int a=5;
  7. clrscr();
  8. while(a!=0)
  9. {
  10. scanf("%d",&a);
  11. }
  12. getch();
  13. }

Program working steps

  • First 7 lines of the program are common about comment, preprocessor directives, void main function, initialization and clearing the console screen.
  • As we have declared the value of a = 5, the while loop statement test expression results true entering the program in while loop body asking for the user to enter the number using scanf statement.
  • When number entered by the user is 0, the loop and program terminates.