C++ while loop

In C++, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. The loop checks the condition before each iteration, and if the condition is true, the code inside the loop is executed. Once the condition becomes false, the loop terminates.

The simplest form of a looping statement is the while loop. Here’s what the while loop looks like:
while(condition)
{
// … repeatedly executed as long as condition is true
}

Syntax:


while (condition)
{
    // Code to execute as long as condition is true
}

Explanation:

condition: A boolean expression that is checked before each iteration. If it is true, the loop continues; if false, the loop terminates.

Note: If the condition is false initially, the loop won’t execute at all.

Example:


#include <iostream>
using namespace std;

int main() {
    int count = 1;
    
    while (count <= 5) {  
        cout << "Count is: " << count << endl;
        count++;  // Increment the count variable to eventually stop the loop
    }
    return 0;
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Explanation:

1. The while loop keeps running as long as count is less than or equal to 5.

2. Each time the loop runs, it prints the value of count and then increments it by 1.

3. The loop will stop once count reaches 6.

C++ while loop – Questions and Answers

Q 1: What is a while loop?

Ans: A loop that executes while a condition is true.

Q 2: Is while loop entry-controlled?

Ans: Yes.

Q 3: What happens if condition is false initially?

Ans: Loop body is not executed.

Q 4: Can while loop run infinitely?

Ans: Yes.

Q 5: When should while loop be used?

Ans: When iterations are unknown.

C++ while loop – Objective Questions (MCQs)

Q1. What is the correct syntax of a while loop in C++?






Q2. When is the condition checked in a while loop?






Q3. What is the output of this code?

int i = 1;
while (i <= 3) {
cout << i << " ";
i++;
}






Q4. What will happen if the condition in a while loop is always false?






Q5. Which of the following can result in an infinite loop?






Related C++ while loop Topics