The perfect place for easy learning...

C Programming Language

×

Topics List

Place your ad here

'while' statement in C

Consider a situation in which we execute a single statement or block of statements repeatedly for required number of times. Such kind of problems can be solved using looping statements in C. For example, assume a situation where we print a message for 100 times. If we want to perform that task without using looping statements, we have to either write 100 printf statements or we have to write the same message for 100 times in a single printf statement. Both are complex methods. The same task can be performed very easily using looping statements.

The looping statements are used to execute a single statement or block of statements repeatedly until the given condition is FALSE.

C language provides three looping statements...

  • while statement
  • do-while statement
  • for statement

while Statement

The while statement is used to execute a single statement or block of statements repeatedly as long as the given condition is TRUE. The while statement is also known as Entry control looping statement. The while statement has the following syntax...

The while statement has the following execution flow diagram...

At first, the given condition is evaluated. If the condition is TRUE, the single statement or block of statements gets executed. Once the execution gets completed the condition is evaluated again. If it is TRUE, again the same statements gets executed. The same process is repeated until the condition is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution control moves out of the while block.

Example Program | Program to display even numbers upto 10.

#include<stdio.h>
#include<conio.h>

void main(){
   int n = 0;
   clrscr() ;
   printf("Even numbers upto 10\n");
   
   while( n <= 10 )
   {
      if( n%2 == 0)
         printf("%d\t", n) ;
      n++ ;
   }
   
   getch() ;
}

Output:

switch in c programming

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use while statement, we must follow the following...

  • while is a keyword so it must be used only in lower case letters.
  • If the condition contains variable, it must be assigned a value before it is used.
  • The value of the variable used in condition must be modified according to the requirement inside the while block.
  • In while statement, the condition may be a direct integer value, a variable or a condition.
  • A while statement can be an empty statement.

Place your ad here
Place your ad here