While loop in cpp

While loop in cpp is simple looping statement.

Looping statement is used to iterate the statement (executed statement multiple times) with some condition.

While loop :- while loop executes the expression before every loop.

It contains condition if condition is true then statement in while loop get executed

and while loop checks condition after every loop.

If the condition is initially false then statement in while loop will not executed.

We write any number of statement in while loop enclosed in curly braces { }.

while loop syntax

while(expression)

{

//Statement 1;

. .

Statement n;

}

In above syntax we can see while having condition if condition is true then only statement in while loop are executed.

while loop example

while(1) {

cout<<“technical seek”;

}

In above Example while (1) , 1 indicates condition true so the statement in while executed.

while loop execution  : while loop executed if and only if condition is true.

while loop program in cpp

123456789101112131415161718192021222324252627#include <iostream>using namespace std;int main(){int i;i=5;cout<<“while loop execution”;while( i > 0 ) //if condition is true{cout<<” i = “<<i<<endl;i –; // Decrement value of i}cout<<“while completed “;    return 0;}

Output :

while loop
while loop

Program description

1. In above program we written while loop to print value of i.

2. First we take initial value of i = 5

3. next we write while loop while(i > 0) , now condition is checked i=5 > 0 this condition is true so statement in while loop executed for first time.

4. In while we decremented value of i i.e i–.now value of i=4.

5. Again execution goes to while condition . Condition checked while(i>0), i=4>0 ,condition gets true and executes statement in while loop.

6. Similarly loop iterated till value of i=0.

7. In case i=0 when while condition is checked condition gets false so execution comes out of the loop and rest statement gets executed.