Loops — Comparison of Loop Structures
I. In-Class Exercises
Programming Exercises
- Sum and Average of Integers: L1131
- Times Divisible by 2: L1132
- Find the Value of s: L1133
- Xiao Ming's Lucky Number: L1134
- Prime Number Check: L1135
Sample Code
1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int n;
5 cin >> n;
6 int sum = 0;
7 for (int i = 1; i <=n; ++i) {
8 int number;
9 cin >> number;
10 sum += number;
11 }
12 double average = 1.0 * sum / n;
13 printf("%d %.5f", sum, average);
14 return 0;
15}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int n;
5 cin >> n;
6 int count = 0;
7 while (n % 2 == 0) {
8 ++count;
9 n = n / 2;
10 }
11 cout << count << endl;
12 return 0;
13}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int now = 1;
5 int add = 0;
6 int sum = 0;
7 while (sum <= 5000) {
8 sum += now;
9 ++add;
10 now += add;
11 }
12 cout << sum << endl;
13 return 0;
14}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int k, l, r;
5 cin >> k >> l >> r;
6 int sum = 0;
7 for (int i = l; i <= r; ++i) {
8 if (i % 10 == k || i % k == 0) {
9 sum += i;
10 }
11 }
12 cout << sum << endl;
13 return 0;
14}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int n;
5 cin >> n;
6 bool flag = true;
7 for (int i = 2; i * i <= n; ++i) {
8 if (n % i == 0) {
9 cout << i << endl;
10 flag = false;
11 break;
12 }
13 }
14 if (flag) {
15 cout << "Yes" << endl;
16 }
17 return 0;
18}II. Knowledge Summary
✨ Review of Three Loop Structures
In previous lessons, we learned three loop structures. Let's review their syntax:
for (initialization; condition; update) {
Loop body
}initialization
while (condition) {
Loop body
update
}initialization
do {
Loop body
update
} while (condition);✨ Comparing the Three Loops
Key Differences
| for loop | while loop | do-while loop | |
|---|---|---|---|
| Check timing | Check first, then execute | Check first, then execute | Execute first, then check |
| Minimum executions | 0 | 0 | 1 |
| Structure | Initialization, condition, update on one line | Three parts scattered | Body before condition |
| Use case | Known iteration count | Unknown count, condition-dependent | Must execute at least once |
for Loop Use Cases
The for loop is typically used when the number of iterations is known, with all three parts on one line for a clear structure.
for (int i = 1; i <= n; ++i) {
cout << i << endl;
}while Loop Use Cases
The while loop is suitable when the number of iterations is unknown and depends on a dynamic condition.
Condition-driven loop: When iteration count depends on a runtime condition
// Keep dividing by 2 until not divisible
while (n % 2 == 0) {
n = n / 2;
++count;
}Waiting for a specific event: Loop until a certain condition is met
int n;
while (cin >> n && n != 0) {
cout << n << endl;
}Infinite loop: Used with break; the exit decision is made inside the loop
1while (true) {
2 int n;
3 cin >> n;
4 if (n == 0) {
5 break;
6 }
7}do-while Loop Use Cases
The do-while loop is suitable for scenarios where at least one execution is required, such as input validation — you must first let the user input, then check if it's valid.
1int n;
2do {
3 cout << "Enter a positive integer: ";
4 cin >> n;
5} while (n <= 0); // Continue prompting if invalid
6cout << "You entered: " << n << endl;✨ How to Choose a Loop Structure
In practice, follow this thought process to choose the right loop:
- Do you know how many times to loop? Yes → Use a for loop
- Don't know, but need at least one execution? Yes → Use a do-while loop
- Don't know, and it might not execute at all? Yes → Use a while loop
In practice, all three loops can be converted to each other. The choice mainly depends on which form is clearest and most readable.
✨ Comprehensive Example: Sum of Digits (Three Approaches)
Solve the same problem with all three loops: input a positive integer and find the sum of its digits. For example, input 123, output 6 (1+2+3=6).
while Implementation
1int n, sum = 0;
2cin >> n;
3while (n > 0) {
4 sum += n % 10;
5 n /= 10;
6}
7cout << sum << endl;for Implementation
1int n, sum = 0;
2cin >> n;
3for (; n > 0; n /= 10) {
4 sum += n % 10;
5}
6cout << sum << endl;do-while Implementation
1int n, sum = 0;
2cin >> n;
3do {
4 sum += n % 10;
5 n /= 10;
6} while (n > 0);
7cout << sum << endl;Comparison Summary
| while | for | do-while | |
|---|---|---|---|
| Flow | Check n>0 first, then get remainder | Check n>0 first, then get remainder | Get remainder first, then check n>0 |
| When n=0 | Loop doesn't execute, sum=0 | Loop doesn't execute, sum=0 | Executes once, sum=0 |
| Code style | Most straightforward | More compact (update in for header) | Guarantees at least one execution |
The flowcharts for while and for are nearly identical because a for loop is essentially syntactic sugar for a while loop. The do-while differs in executing before checking. However, for positive integer inputs, all three produce the same result.