C++ Beginner

cpp_009: While Loops and Break Statement in C++

codeaddict 2025. 1. 15. 22:41

Loops allow for repeated execution of code blocks, and the while loop is a foundational construct in C++ for controlling repetition based on a condition. In this lesson, we’ll cover the syntax of the while loop, demonstrate a basic example, and introduce the break statement for enhanced control flow.


1. While Loop Syntax

A while loop in C++ repeatedly executes a block of code as long as its condition evaluates to true.

while (condition) {
    // Code block to execute
}
  • Condition: The loop continues to run as long as this evaluates to true.
  • The loop terminates when the condition becomes false.

2. Example 1: Basic While Loop

This example prints numbers from 1 to 5 using a while loop.

#include <iostream>
using namespace std;

int main() {
    int i = 1;  // Initialization
    while (i <= 5) {  // Condition
        cout << "Number: " << i << endl;
        i++;  // Increment
    }
    return 0;
}

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

Explanation:

  1. The loop starts with i = 1.
  2. The condition i <= 5 ensures the loop runs five times.
  3. The i++ increments the variable i with each iteration, moving toward the loop's termination.

3. Example 2: Using break in a While Loop

The break statement is used to exit a loop prematurely, regardless of the condition. Here’s an example that demonstrates how to use it effectively.

#include <iostream>
using namespace std;

int main() {
    int i = 1;  // Initialization
    while (true) {  // Infinite loop
        if (i > 5) {  // Break condition
            break;
        }
        cout << "Number: " << i << endl;
        i++;
    }
    return 0;
}

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

Explanation:

  1. The while (true) creates an infinite loop.
  2. The if (i > 5) checks whether i exceeds 5.
  3. When i > 5, the break statement terminates the loop, skipping the remaining iterations.

Summary

The while loop is a versatile tool for repeating tasks, especially when the number of iterations is not predetermined. The break statement enhances its flexibility, allowing you to exit the loop under specific conditions.