C++ System Learning Without Textbooks: 04 Loop Statements (Part 1)

<Loop Statements (Part 1)>From beginner to expert, from Hello World to ACMAll content, no textbooks required!

Course Objectives:

Understand the concept of loops and their importance in program design.

Master the syntax and execution flow of <span>for</span> loops and <span>while</span> loops.

Be able to use loop control statements <span>break</span> and <span>continue</span> to flexibly control loops.

Be able to apply loop structures to solve simple problems such as summing sequences and counting numbers.

1. Why Do We Need Loops?

Imagine if you had to output 100 lines of <span>"Hello, World!"</span> on the screen, how would you do it?

If there were no loops, you might need to write 100 <span>cout</span> statements. This is not only tedious but also prone to errors.

Loops exist to solve the problem of needing to repeat similar operations. They allow you to write the code once and have the computer execute it multiple times. Loops are fundamental for processing bulk data and performing iterative calculations.

2. For Loop: Counting Loop

<span>for</span> loops are the best choice when you know exactly how many times you need to repeat. Their structure is very clear, concentrating all control logic within a single set of parentheses.

1. Basic Syntax

for (initialization; loop condition; update) {    // Loop body: code to be repeated}

  • Initialization: Executed once before the loop starts, usually used to initialize a counter.

  • Loop Condition: Evaluated before each loop iteration. If true (<span>true</span>), the loop body is executed; if false (<span>false</span>), the loop ends.

  • Update: Executed after each loop body execution, usually used to update the counter.

2. Execution Flow

<span>Initialization</span> -> Evaluate <span>Condition</span> -> (if true) Execute <span>Loop Body</span> -> Execute <span>Update</span> -> Evaluate <span>Condition</span> -> …

Practical Example 1: Output integers from 1 to 100

#include <iostream>using namespace std;int main() {    for (int i = 1; i <= 100; i++) { // i starts at 1, ends at 100, incrementing by 1 each loop        cout << i << endl;    }    return 0;}

Common Mistakes:

    • Loop Condition:<span>i <= 100</span> means including 100. If written as <span>i < 100</span>, it will only output from 1 to 99.

    • Boundary Traps: This is the most error-prone area in loop problems; be sure to confirm the starting value and ending condition of the loop.

3. Flexibly Using For Loops

The three parts of a for loop can be very flexible. For example, to calculate the sum of all odd numbers from 1 to 100:

#include <iostream>using namespace std;int main() {    int sum = 0; // Initialize an accumulator    for (int i = 1; i <= 100; i += 2) { // i starts at 1, incrementing by 2 (1, 3, 5, ...)        sum += i; // Equivalent to sum = sum + i;    }    cout << "Sum of odd numbers: " << sum << endl;    return 0;}
  • Key Concept: Accumulator: A variable (like <span>sum</span>) is usually defined before the loop to store cumulative results, typically initialized to 0.

3. While Loop: Conditional Loop

<span>while</span> loops are suitable for situations where the exact number of iterations is unknown, but the condition for continuing the loop is known.

1. Basic Syntax

while (loop condition) {    // Loop body}

  • As long as the <span>loop condition</span> is true, the loop body will be executed repeatedly.

Practical Example 2: Counting the Number of Digits

Input a positive integer and count how many digits it has.

#include <iostream>using namespace std;int main() {    int n, count = 0;    cin >> n;    int temp = n; // Use a temporary variable to operate, preserving the original input n    while (temp > 0) {        count++;       // Increment digit count        temp /= 10;    // Remove the last digit (e.g., 123 becomes 12)    }    cout << n << " has: " << count << " digits" << endl;    return 0;}


Common Questions:: Why use <span>temp</span> instead of the original <span>n</span>? Answer: Because we modify (

<span>temp /= 10</span>) this variable during the loop. If we directly use <span>n</span>, the original input data would be corrupted, and the final output would not be the original number. This is a good programming practice.

Choosing Between For and While

  • When the number of iterations is clear: use <span>for</span> (e.g., traversing an array, calculating the sum from 1 to 100).
  • When the number of iterations is unknown and depends on a condition: use <span>while</span> (e.g., continuously reading data until the end of a file, game loops until the player exits).

4. Loop Control: Break and Continue

Sometimes we need to intervene in the middle of a loop.

  • break: Immediately terminate the entire loop, exiting the loop body.
  • continue: Skip the remaining statements in the current loop iteration, directly proceed to the next iteration.

Practical Example 3: Checking for Prime Numbers

Input a positive integer and determine if it is a prime number.

#include <iostream>#include <cmath> // Include cmath header for sqrt functionusing namespace std;int main() {    int n;    bool isPrime = true; // Assume it is prime initially    cin >> n;    if (n <= 1) {        isPrime = false;    } else {        for (int i = 2; i <= sqrt(n); i++) { // Optimization: only check up to sqrt(n)            if (n % i == 0) {                isPrime = false;                break; // Finding one factor is enough to prove it's not prime, terminate the loop immediately            }        }    }    if (isPrime) {        cout << n << " is prime" << endl;    } else {        cout << n << " is not prime" << endl;    }    return 0;}

Application of break: Once it is found that n can be divided by some number, break immediately, no need to check further numbers, improving efficiency.Example of continue: Output numbers from 1 to 10 that are not multiples of 3.

for (int i = 1; i <= 10; i++) {    if (i % 3 == 0) {        continue; // If it is a multiple of 3, skip the following cout, directly i++    }    cout << i << " "; // Output: 1 2 4 5 7 8 10}

Please write a program that inputs an integer n and calculates the value of 1!+2!+3!++n! (i.e., the sum of factorials from 1 to n).

(Hint: You need an outer loop to iterate from 1 to n, and an inner loop to calculate the factorial of each number. Think about the structure first; the answer will be provided after class.)

Summary and Key Points of This Lesson

• For loops are used for counting loops, with a compact structure.

• While loops are used for conditional loops, offering more flexibility.• Break is used to completely end a loop, while <span>continue</span> is used to skip the current iteration.

  • Common Mistakes:

1. Infinite Loops: Ensure that the loop condition can eventually become false; otherwise, the program will run indefinitely. For example, <span>while (1) {...}</span> without a break is an infinite loop.2. Uninitialized Loop Variables: Especially be cautious of the scope when using counter <span>i</span> outside of a <span>for</span> loop.3. Boundary Errors: Carefully check the starting and ending conditions of the loop.

Homework

Homework Objectives: Master the use of loop statements to solve practical problems and develop logical thinking.

Homework 1: Basic Consolidation

  1. Sum of a Sequence: Calculate the sum of 12+34++(1)n+1n (Luogu P5743).
  2. Reverse a Number: Input an integer and output its digits in reverse order.

For example, input

1230

output

321

(Luogu P1307, be careful to handle trailing zeros and negative numbers).

Homework 2: OJ Practice

  1. [Luogu P1420 Longest Consecutive Numbers]: Find the length of the longest consecutive increasing sequence in a series of numbers, very suitable for solving with loops.

  2. [Luogu P1423 Xiaoyu Swimming]: Xiaoyu happily swims, and she needs to swim to a target distance. Calculate how many steps she needs to swim. This is a typical problem that simulates a process using loops.

  3. (Challenge) [Luogu P1217 [USACO1.5] Palindromic Primes]: Find all numbers that are both palindromic and prime within a given range. This problem integrates loops, conditions, and functions (try it in advance), and is quite challenging.

Answers to In-Class Tests:

#include <iostream>using namespace std;int main() {    int n;    long long totalSum = 0; // Total sum may be large, use long long    cin >> n;    for (int i = 1; i <= n; i++) { // Outer loop: iterate from 1 to n        long long factorial = 1; // Calculate factorial of i        for (int j = 1; j <= i; j++) { // Inner loop: calculate factorial            factorial *= j;        }        totalSum += factorial; // Add factorial to total sum    }    cout << totalSum << endl;    return 0;}// Thought: Can this algorithm be optimized? (Hint: 5! = 4! * 5, can avoid the inner loop)


Answers to Homework:

Homework 1:

1. Sequence Sum Program (P5743) Key Points::

int n, sum = 0;cin >> n;for (int i = 1; i <= n; i++) {    if (i % 2 == 1) { // Odd terms are positive        sum += i;    } else { // Even terms are negative        sum -= i;    }}// Or a more clever method: determine the sign based on the odd/even nature of the term// for (int i = 1; i <= n; i++) {//     if (i % 2 == 1) {//         sum += i;//     } else {//         sum -= i;//     }// }cout << sum << endl;

2. Number Reversal Program (P1307) Key Points:

#include <iostream>using namespace std;int main() {    int n, reversed = 0;    cin >> n;    // Handle negative numbers: first record the sign, then process as a positive number    bool isNegative = (n < 0);    if (isNegative) n = -n;    while (n > 0) {        reversed = reversed * 10 + n % 10; // Core reversal logic        n /= 10;    }    if (isNegative) reversed = -reversed;    cout << reversed << endl;    return 0;}


Key Points for OJ Problems:

P1420 Longest Consecutive Numbers:: Traverse the array, using a variable <span>current</span> to record the current consecutive length, and another variable <span>max</span> to record the longest consecutive length encountered. If the next number is one greater than the previous, increment <span>current</span>; otherwise, reset <span>current</span> to 1 and update <span>max</span>.

P1423 Xiaoyu Swimming:: Simulate the swimming process using loops. Set a variable <span>distance</span> to represent the distance swum, and another variable <span>step</span> to represent the number of steps. In each loop, the distance swum is 0.98 times the previous step until the total distance reaches the target.

P1217 Palindromic Primes:: This is a comprehensive problem. The idea is to traverse each number within the given range, first checking if it is a palindromic number (by reversing the number and comparing), and if so, checking if it is prime (using the optimization method learned in this lesson).

In the next lesson, we will learn:

“Applications and Practices of Loops”

If you have questions, feel free to comment!

Follow YunJie Algorithm, no textbooks needed, just a finger tap to systematically learn programming!

Leave a Comment