C++ while loop with Examples


While loop in C++ executes the specific block of statements until the condition becomes false. Loops in C++ are used to execute the given block of the statement until the condition fails.

How while loop works

In While loop first, the condition is evaluated. If the condition returns true value then the code inside the loop executes. This process is repeated until the condition becomes false. When the condition becomes false the control comes out of the loop and executes next statement in program.

Basic Syntax

Following is the basic syntax for while loop in C++:

while (condition)
{
//code statements…
}

Where,

Name Description
condition It can be any expression
code statements… A single statement or block of statements to execute

Example

Following are example illustrating while loop in C++.

// program for illustrating 
#include <iostream>

using namespace std;

int main(){
   // numbers array
   int numbers[] ={1,34,26,58,63,13,27,90,10,90};
   int i = 0;
   
   cout << "Print All Array Elements: ";
   
   // printing all numbers in array using while loop
   while(i < 10){
      cout<<numbers[i]<<endl; 
      i++;
   }
}

The output for the above program is as given below:

Print All Array Elements: 1
34
26
58
63
13
27
90
10
90