C++ while/do-while Loop
In this tutorial, we will learn about the C++ loops, while loop, do-while, nested while/do-while loop difference, and infinite while/do-while loop and its working with the help of some examples.
C++ Loops
In computer programming, loops are used to repeat a block of code. Loops in Programming come into use when we need to repeatedly a block of statements.
For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.
In programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
Types of Loops
There are 3 types of loops in C++:
1) for
loop
2) while
loop
3) do...while
loop
In the previous tutorial, we learned about the C++ for loop. Here, we are going to learn about while
and do...while
loops.
C++ while Loop
- A
while
is a Entry Controlled Loop or we can say repetition control structure. - The
while
loop is used in situations where we do not know the exact number of iterations of loop beforehand. - The loop execution is terminated on the basic of the test condition.
Working of while loop
- A
while
loop evaluates thecondition
. - If the
condition
evaluates totrue
, the code inside thewhile
loop is executed. - The
condition
is evaluated again. - This process continues until the
condition
isfalse
. - When the
condition
evaluates tofalse
, the loop terminates.
The syntax of the while
loop is:
while (condition) {
// body of the loop
}
To learn more about the conditions
, visit C++ Relational and Logical Operators.
Flowchart of while Loop
Example 1: Program to print "Hello world!" 3 times
#include <iostream>
using namespace std;
int main() {
// Initialization expression
int i = 1;
// test expression
while (i < 4) {
cout <<"Hello World\n ";
// update expression
i++;
}
return 0;
}
Output
Hello World Hello world Hello world
Let's understand how the program works.
Iteration | Variable | i <= 3 | Action |
---|---|---|---|
1st | i = 1 |
true |
Hello World is printed and i is increased to 2 . |
2nd | i = 2 |
true |
Hello World is printed 2nd time and i is increased to 3 . |
3rd | i = 3 |
true |
Hello World is printed 3rd time and i is increased to 4 |
4th | i = 4 |
false |
The loop is terminated |
Example 2: C++ Sum of Positive Integers Only
#include <iostream>
using namespace std;
int main() {
// declare and initialize vector
vector<int> num = {1, 2, 3, 4, 5, 6};
// print vector elements
for (int i : num) {
cout << i << " ";
}
return 0;
}
Output
1 2 3 4 5 6
Example 3: Declare Collection inside the Loop
// program to find the sum of positive Integers
// if the user enters a negative Integers, the loop ends
// the negative integer entered is not added to the sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive integers
sum += number;
// take input again if the integer is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum of all the positive integers
cout << "\nThe sum of positive integers: " << sum << endl;
return 0;
}
Output
Enter a number: 6 Enter a number: 6 Enter a number: 10 Enter a number: 0 Enter a number: -12 The sum of positive integers: 22
Working of this program:
- In this program, the user entered a number, which is stored in the variable number.
- In order to store the sum of the numbers, we declare a variable sum and initialize it to the value of
0
. - The
while
loop continues until the user enters a negative number. - During each iteration, the number entered by the user is added to the sum variable.
- When the user enters a negative number, the loop terminates.
- Finally, the total sum is displayed.
C++ Nested while Loop
A while loop within another while loop is called Nested while loop.
The syntax of nested while loop is:
while (condition) {
while (condition) {
// body of inner while-loop
}
// body of outer while-loop
}
Example 4: Program to display a triangular pattern
// C++ program to display a triangular pattern
#include <iostream>
using namespace std;
int main() {
int rows, i = 1;
cout << "Enter the number of rows: ";
cin >> rows;
while (i <= rows) {
int j = 1;
while(j <= i) {
cout << "* ";
j++;
}
cout << "\n";
i++;
}
return 0;
}
Enter the number of rows: 4 * * * * * * * * * *
In this program, the outer loop iterates from 1
to rows.
The inner loop iterates from 1
to i. Inside the inner loop, we print the character '*'
.
- Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level.
- If you don't understand above example, We recommended you to know little more about Nested Loop.
C++ do...while Loop
- Like
while
loop thedo-while
loop execution is also terminated on the basic of a test condition. - The
do-while
loop is exit-controlled loop. - in do-while loop the loop body will execute at least once irrespective of test condition.
Working of do-while loop
- The body of the loop is executed at first. Then the
condition
is evaluated. - If the
condition
evaluates totrue
, the body of the loop inside thedo
statement is executed again. - The
condition
is evaluated once again. - If the
condition
evaluates totrue
, the body of the loop inside thedo
statement is executed again. - This process continues until the
condition
evaluates tofalse
. Then the loop terminates.
The syntax of do-while loop is:
do {
// body of loop;
}
while (condition);
Flowchart of do...while Loop
Example 5: Display Numbers from 1 to 4
// C++ Program to print numbers from 1 to 4
#include <iostream>
using namespace std;
int main() {
// Initialization expression
int i = 1;
// do...while loop from 1 to 4
do {
cout << i << " ";
++i;
}
// test expression
while (i <= 4);
return 0;
}
Output
1 2 3 4
Here is how the program works.
Iteration | Variable | i <= 4 | Action |
---|---|---|---|
i = 1 |
not checked | 1 is printed and i is increased to 2 |
|
1st | i = 2 |
true |
2 is printed and i is increased to 3 |
2nd | i = 3 |
true |
3 is printed and i is increased to 4 |
3rd | i = 4 |
true |
4 is printed and i is increased to 5 |
4th | i = 5 |
false |
The loop is terminated |
Example 6: Sum of Positive Numbers Only using do-while loop
// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum
#include <iostream>
using namespace std;
int main() {
int num = 0, sum = 0;
do {
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> num;
}
while (num >= 0);
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}
Output 1
Enter a number: 6 Enter a number: 12 Enter a number: 7 Enter a number: 0 Enter a number: -2 The sum is 25
Here, the do...while
loop continues until the user enters a negative number. When the number is negative, the loop terminates; the negative number is not added to the sum
variable.
Output 2
Enter a number: -6 The sum is 0.
The body of the do...while
loop runs only once if the user enters a negative number.
Nested do-while Loop
A do-while loop within another do-while loop is called Nested do-while loop.
The syntax of nested do-while loop is:
do {
do{
// body of inner do-while-loop
}while (condition);
// body of outer do-while-loop
}while (condition);
Example 7: program to display a triangular pattern using nested do-while
// C++ program to display a triangular pattern
#include <iostream>
using namespace std;
int main() {
int rows, i,j;
i = 1;
cout << "Enter the number of rows: ";
cin >> rows;
do {
j = 1;
do{
cout << "* ";
j++;
}while(j <= i);
cout << "\n";
i++;
}while(i <= rows);
return 0;
}
Output
Enter the number of rows: 4 * * * * * * * * * *
for loop vs while loop
for loop | while loop |
---|---|
Initialization may be either in loop statement or outside the loop. | Initialization is always outside the loop. |
Once the statements is executed then after increment is done. | Increment can be done before or after the execution of the statement. |
It is normanlly used when the number of iteration is known. | It is normally used when the number of iterations is unknown. |
Condition is a relational expression. | Condition may be expression or non-zero value. |
It is used when initialization and increment is simple. | It is used for complex initialization. |
For is entry Controlled loop. | while is also entry controlled loop. |
for (initialization; condition; iteration) {statement(s);} | while(condition){statement(s);} |
for loop used only when we already knew the number of iterations. | while loop used only when the number of iteration are not exactly known. |
while loop vs do-while loop
while loop | do-while loop |
---|---|
Condition is checked first then statement(s) is executed | Statement(s) is executed atleast once, thereafter condition is checked. |
It might occur statement(s) is executed zero times, if condition is false. | Atleast once the statement(s) is executed. |
No semicolon at the end of while. while(condition) | Brackets are always rewuired. |
Variable in condition is initialized before the execution of loop. | Variable may be initialized before or within the loop. |
while loop is entry controlled loop. | do-while loop is exit controlled loop. |
while(condition){statement(s);} | do{statement(s)}while(condition); |
The iteration do not occur if, the condition at the first iteration, appears false. | The iteration occurs atleast once even if the condition is false at the first iteration. |
Check out these examples to learn more:
Next Tutorial
We hope that this tutorial helped you develop better understanding of the concept of While/do...while Loop in C++.
Keep Learning : )
In the next tutorial, you'll learn about C++ break Statement
.