‘while’ statement in C
Let us 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 by using looping statements in ‘C’.
For example, assume a situation where we want to print a message for 100 times. If we want to perform that task without using looping statements, we must have to either write 1000 printf statements or we shall have to write the same message for 1000 times in a single printf statement. Both the methods are very complicated and more time consuming . The same task can be done very easily using looping statements. Advantage of using looping statement is tosave a lot of time and make the problem very easy to solve. It also saves the space block sheet.
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
1)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.
Syntax of ‘while’ statement is :-
SYNTAX : while (condition)
{
……………
block of statements ;
or group of statements;
…………..
}
Flow chart diagram of the while statement is given below…
In the above given flow chart diagram, the given condition is evaluated firstly.
If the condition is’ TRUE’, the statements (single or block/group of statements) gets executed. And once the execution is being completed, the condition will again evaluated.
If the condition is ‘TRUE’, again the same statements would be executed. The same process will repeat simultaneously until the condition is evaluated to ‘FALSE’. Whenever the condition is ‘FALSE’, the execution control will escape out of the while block.
Example: | Write a program to display even numbers upto 10 as an output.
#include<stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf(“Even numbers from 0 to 10\n”);
while( n <= 10 )
{
if( n%2 == 0)
printf(“%d\t”, n) ;
n++ ;
}
getch();
}
Output:
Even numbers from 0 to 10
0 2 4 6 8 10
VVI POINTS THAT IS NECESSORY TO KNOW ABOUT ‘while STATEMENT’
We must have to follow the following condition, when we use while statement:-
- ‘while’ is a keyword therefore it must be used only in lower case letters.
- If the condition keeps variable, it must be assigned a variable value before it is used.
- The value of the variable used in the condition must be modified/arranged 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 also be an empty statement.