Search Your Topic

config
Monday, 12 June 2017 01:41

C++ While loop

Written by
Rate this item
(0 votes)

In C++, while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop than for loop.

 
  1. while(condition){    
  2. //code to be executed    
  3. }    

Flowchart:

Cpp While loop 1


C++ While Loop Example

Let's see a simple example of while loop to print table of 1.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main() {         
  4.  int i=1;      
  5.          while(i<=10)   
  6.        {      
  7.             cout<<i <<"\n";    
  8.             i++;  
  9.           }       
  10.     }  

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested While Loop Example

In C++, we can use while loop inside another while loop, it is known as nested while loop. The nested while loop is executed fully when outer loop is executed once.

Let's see a simple example of nested while loop in C++ programming language.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main () {  
  4.         int i=1;      
  5.           while(i<=3)     
  6.           {    
  7.               int j = 1;    
  8.               while (j <= 3)    
  9. {      
  10.             cout<<i<<" "<<j<<"\n";      
  11.             j++;  
  12.           }     
  13.            i++;  
  14.         }  
  15.     }    

Output:

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

C++ Infinitive While Loop Example:

We can also create infinite while loop by passing true as the test condition.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main () {  
  4.         while(true)  
  5.           {    
  6.                   cout<<"Infinitive While Loop";    
  7.           }    
  8.     }    

Output:

Infinitive While Loop 
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c
Read 159 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in
More in this category: « C++ For Loop C++ Do-While Loop »

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.