while statement in C++ | while loop in C++

while statement in C++ | while loop in C++

It is an entry controlled looping statement. It is basically used when we may not be aware of how many times the loop will execute. In while statement, initialization, condition and updation are performed in different lines. The syntax of while statement is:

Initialization;
while(Condition)
{
  Statement-Block;
  Updation;
}

while is a keyword to specify the beginning of while statement.

Initialization is the way to assign some initial value to loop control variable This is the value from where while statement starts.

Example

i=1;

Condition: It refers to any relational or logical expression used to check whether the loop should continue or not.

Example

i<=5;

Update: It is the way to increase or decrease the value of control variable.

Example

i++

Statements-Block  refers to set of C+++ statements which will repeatedly execute as long as condition is true.

 

Program to demonstrate the use of while statement in C++. 
#include<stdio.h>
int main()
{
int k;
k=1;
while(k<=4)
{
  cout<<endl<<k;
  k++;
}
return(0);
}
Output
1
2
3
4
5

Description of above program

In the program, control variable k has been strored value 1. Value of k is then compared with 4. It is less than equal to  4, so statement cout<<endl<<i;  gets executed displaying value of k i.e. 1.

Then control goes to updation statement k++which increases the value of k by 1. k becomes 2.

Again k<=5 is tested. which is true so cout<<endl<<k; gets executed.

Again updation k++ is performed followed by condition k<=4. This process goes on as long as condition is true.

Spread the love
Lesson tags: program of while statement in c, syntax of while statement in C++, while loop in C++, while statement in c
Back to: C Programming Language
Spread the love