0
0
CppHow-ToBeginner · 3 min read

How to Use While Loop in C++: Syntax and Examples

In C++, a while loop repeatedly executes a block of code as long as the given condition is true. The syntax is while (condition) { /* code */ }, where the condition is checked before each iteration.
📐

Syntax

The while loop syntax in C++ consists of the keyword while, followed by a condition in parentheses, and a block of code inside curly braces. The loop runs the code block repeatedly as long as the condition remains true.

  • condition: A boolean expression checked before each loop iteration.
  • code block: The statements executed each time the condition is true.
cpp
while (condition) {
    // code to repeat
}
💻

Example

This example prints numbers from 1 to 5 using a while loop. It shows how the loop runs while the condition count <= 5 is true, increasing count each time.

cpp
#include <iostream>

int main() {
    int count = 1;
    while (count <= 5) {
        std::cout << count << std::endl;
        count++;
    }
    return 0;
}
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes with while loops include:

  • Forgetting to update the variable in the condition, causing an infinite loop.
  • Using the wrong condition that never becomes false.
  • Placing the update statement outside the loop accidentally.

Always ensure the loop condition will eventually become false to stop the loop.

cpp
/* Wrong: Infinite loop because count is never updated */
#include <iostream>

int main() {
    int count = 1;
    while (count <= 5) {
        std::cout << count << std::endl;
        // Missing count++ here
    }
    return 0;
}

/* Correct: Updates count inside the loop */
#include <iostream>

int main() {
    int count = 1;
    while (count <= 5) {
        std::cout << count << std::endl;
        count++;
    }
    return 0;
}
📊

Quick Reference

Remember these tips when using while loops in C++:

  • Check the condition before each iteration.
  • Make sure the condition will become false eventually.
  • Update variables inside the loop to avoid infinite loops.
  • Use while when the number of iterations is not known in advance.

Key Takeaways

Use while loops to repeat code while a condition is true.
Always update variables inside the loop to avoid infinite loops.
The condition is checked before each iteration, so the loop may not run if false initially.
Use while loops when you don't know how many times the loop should run in advance.