CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

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

  • //Using while loop statement
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • int a=5;
  • clrscr();
  • while(a!=0)
  • {
  • scanf("%d",&a);
  • }
  • getch();
  • }

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.

Tip Box

You can create a while loop that will never end by using number 1. Since 1 is always true, the loop will continue unless break statement is reached in the loop body.


Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved