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:
- The loop starts with i = 1.
- The condition i <= 5 ensures the loop runs five times.
- 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:
- The while (true) creates an infinite loop.
- The if (i > 5) checks whether i exceeds 5.
- 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.
'C++ Beginner' 카테고리의 다른 글
cpp_011: Understanding the sizeof Operator in C++ (0) | 2025.02.01 |
---|---|
cpp_010: Arrays in C++ (0) | 2025.01.26 |
cpp_008: for Loops in C++ (0) | 2025.01.12 |
cpp_007:Introduction to String Modifiers in C++ , Mastering String Manipulation (1) | 2025.01.06 |
cpp_006_Introduction to getline and cin.getline in C++: Handling User Input with Spaces (0) | 2025.01.05 |