What is While loop in C++ | Syntax of while Loop
While loop is the simplest loop of C++ language. While loop executes more statements while the given condition will be true. It is useful when the number of iterations is not known in advance.
Syntax of while Loop
The syntax of the while loop is as follows:
while (condition)
statement;
condition: The condition is given as a relational expression. While loop executes statements when the given condition will be true. If the condition is false, the statement is never executed.
Statement: The statement is the instruction that is executed when the condition is true. If two or more statements are used, these are given in braces { }. It is called the body of loop.
The syntax for compound statements is as follows:
while (condition)
{
Statement 1;
Statement 2;
.
.
Statement N;
}
Working of ‘While’ Loop
First of all, the condition is evaluated. If it is true, the control enters the body of the loop and executes all statements in the body. After executing the statements, it again moves to the start of the loop and evaluates the condition again.
This process continues as long as the condition remains true. When the condition becomes false, the loop is terminated. While the loop terminates only when the condition becomes false.
If the condition remains true, the loop never ends. A loop that has no endpoint is known as an infinite loop.
Flowchart
Example
#include <iostream.h>
#include <conio.h>
Void main()
{
int n;
clrscr ()؛
n = 1
while (n <= 5)
{
cout << ” Pakistan”<<endl;
n++;
}
getch();
}
Output
Pakistan
Pakistan
Pakistan
Pakistan
Pakistan
#include <iostream.h>
#include <conio.h>
Void main()
{
int n;
clrscr ()؛
n = 1
while (n <= 10)
{
cout << n <<endl;
n++;
}
getch();
}
Output
1
2
3
4
5
6
7
10
Leave a Reply