C++ while loop
In this article, we will learn the usage of while
loop in C++ programming. Through various examples, we will gain a better understanding of how these loops work and how they can be utilized in our programs.
Loops are a fundamental component of computer programming, allowing us to repeat a specific block of code multiple times. In C++, there are three types of loops:
for
loop,while
loopdo...while
loop.
Each type of loop has its own unique features and use cases, and in this tutorial, we will focus on the while
loop.
The while
loop is a control structure in C++ that allows you to repeatedly execute a block of code as long as a specified condition is true. The basic syntax of the while
loop is as follows:
1while (condition) 2{ 3 // code to be executed 4}
Here, the condition
is evaluated before each iteration of the loop, and the loop continues to execute as long as the condition is true. If the condition is false, the loop terminates and the program continues with the next statement after the loop.
Let's take a look at two examples of while
loops in C++ and their output:
Simple While Loop
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int i = 1; 7 while (i <= 5) 8 { 9 cout << "Value of i: " << i << endl; 10 i++; 11 } 12 13 return 0; 14}
In the above example, the while
loop initializes the value of i
to 1 and continues to execute as long as i
is less than or equal to 5. The value of i
is incremented by 1 after each iteration of the loop. The output will be:
1Value of i: 1 2Value of i: 2 3Value of i: 3 4Value of i: 4 5Value of i: 5
Nested While Loop
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int i = 1; 7 while (i <= 3) 8 { 9 int j = 1; 10 while (j <= 2) 11 { 12 cout << "Value of i: " << i << " and j: " << j << endl; 13 j++; 14 } 15 i++; 16 } 17 18 return 0; 19}
In the above example, the outer while
loop initializes the value of i
to 1 and continues to execute as long as i
is less than or equal to 3. The inner while
loop initializes the value of j
to 1 and continues to execute as long as j
is less than or equal to 2. The output will be:
1Value of i: 1 and j: 1 2Value of i: 1 and j: 2 3Value of i: 2 and j: 1 4Value of i: 2 and j: 2 5Value of i: 3 and j: 1 6Value of i: 3 and j: 2