๐ C++ Programming Lesson 11: Combining for and cin, if – Making Loops Smarter

๐ Course Navigation
1ใ๐ค Why Combine? (The “small drawbacks” of fixed loops and the “advantages” of combinations)2ใ๐ Combining for and cin: Letting Users Decide the Loop (Controlling repetition based on input)3ใโก Combining for and if: “Conditional Filtering” in Loops (Only executing operations that meet conditions)4ใ๐งช Comprehensive Case: Solving Real Problems (Practical application of combination usage)5ใโ ๏ธ Common Mistakes in Combinations (Avoiding “disobedient” code)6ใ๐ข Next Lesson Preview: Detailed Explanation of while Loops (A New Way to Control Loops Flexibly)
1. ๐ค Why Combine? – From “Fixed” to “Smart”
In the last lesson, we learned that for loops are mostly “fixed repetitions” – for example, looping a fixed number of times like 5 or 10, similar to “making a fixed number of cakes regardless of whether anyone wants them.” However, many real-life scenarios require “flexible adjustments”:
- ๐ A teacher counting grades: “The number of grades to collect depends on how many students show up today” (requires user input to determine the number of repetitions);
- ๐ A mother selecting apples: “Only picking the red and large ones from 10 apples” (the loop needs to check conditions to filter the desired ones).
At this point, combining the for loop with what we learned earlier about cin (getting user input) and if (conditional judgment) can make the loop “smarter” – it can follow user instructions and also filter itself!
2. ๐ Combining for and cin: Letting Users Decide the Loop
The core of combining for and cin is: using cin to get the “key information” from user input (like the number of repetitions or target number), and then using this information to control the for loop. The most common scenario is “allowing the user to input the number of repetitions and executing operations accordingly”.
Case 1: User Decides Print Count
Requirement: Let the user input a number n and print “I am learning C++!” n times.
#include <iostream>using namespace std;int main() { int n; // Store the user's input for the number of repetitions cout << "Please enter the number of times to print:"; cin >> n; // Get the user's input for n // for loop: repeat n times from 1 to n for (int i = 1; i <= n; i++) { cout << "No." << i << ": I am learning C++!" << endl; } return 0;}
Execution Scenario:
- User inputs 3 โ Outputs “I am learning C++!” 3 times;
- User inputs 5 โ Outputs “I am learning C++!” 5 times.
Key Logic:
The n obtained from cin is directly used in the for loop’s “conditional expression” (i <= n), allowing the user to decide the number of repetitions instead of hardcoding it in the code.
Case 2: User Inputs Numbers, Calculate Sum
Requirement: Let the user input the number of numbers m to calculate, then input m numbers, and finally calculate the sum of these numbers.
#include <iostream>using namespace std;int main() { int m, num, sum = 0; cout << "Please enter the number of numbers to calculate:"; cin >> m; // Step 1: Get the number of numbers m // Step 2: Loop m times, input one number each time and accumulate for (int i = 1; i <= m; i++) { cout << "Please enter number " << i << ":"; cin >> num; // Get one number each time in the loop sum += num; // Add the number to the total } cout << "The sum of these " << m << " numbers is: " << sum << endl; return 0;}
Execution Scenario:
User inputs 3 โ Inputs 10, 20, 30 โ Outputs “The sum is 60”.
3. โก Combining for and if: “Conditional Filtering” in Loops
The core of combining for and if is: adding if statements in the “loop body” of the for loop, allowing the loop to only execute operations for “satisfying conditions”, just like “only picking out the red ones from a pile of toys”.
Case 1: Filtering Even Numbers in a Loop
Requirement: Loop through numbers 1 to 20, printing only the even numbers (numbers divisible by 2).
#include <iostream>using namespace std;int main() { cout << "Even numbers from 1 to 20:"; // Loop from 1 to 20 for (int i = 1; i <= 20; i++) { // if statement: check if divisible by 2 (i % 2 == 0) if (i % 2 == 0) { cout << i << " "; // Print only if condition is met } } return 0;}
Execution Result:
Even numbers from 1 to 20: 2 4 6 8 10 12 14 16 18 20
Key Logic:
The for loop is responsible for “iterating from 1 to 20”, while the if statement is responsible for “filtering even numbers”; only numbers satisfying i%2==0 will be printed.
Case 2: Counting Passing Grades
Requirement: Let the user input the grades of 5 students and count how many passed (grades โฅ 60 are considered passing).
#include <iostream>using namespace std;int main() { int score, passCount = 0; // passCount stores the number of passing students, initialized to 0 // Loop 5 times, input 5 grades for (int i = 1; i <= 5; i++) { cout << "Please enter the grade of student " << i << ":"; cin >> score; // if statement: check if the grade is passing if (score >= 60) { passCount++; // Increment the count of passing students } } cout << "Among the 5 students, the number of passing students is: " << passCount << endl; return 0;}
Execution Scenario:
User inputs 75, 58, 92, 45, 60 โ Outputs “The number of passing students is: 3”.

4. ๐งช Comprehensive Case: Using for, cin, and if Together
Requirement: Let the user input a number n, then print the numbers from 1 to n that are “divisible by 3 but not by 5” (using all three concepts).
#include <iostream>using namespace std;int main() { int n; cout << "Please enter a number n:"; cin >> n; // cin gets n, determining the loop range cout << "Numbers from 1 to " << n << " that are divisible by 3 but not by 5:"; for (int i = 1; i <= n; i++) { // for loop iterates from 1 to n // if statement: divisible by 3 (i%3==0) and not divisible by 5 (i%5!=0) if (i % 3 == 0 && i % 5 != 0) { cout << i << " "; // Print only if condition is met } } return 0;}
Execution Scenario:
User inputs 30 โ Outputs “3 6 9 12 18 21 24 27” (these numbers meet the conditions).
5. โ ๏ธ Common Mistakes in Combinations
Mistake 1: cin written outside the for loop, causing input value to be reused
For example, in Case 2, if cin >> score is written outside the for loop:
// Error: only input once, using this score for all 5 loopscin >> score;for (int i = 1; i <= 5; i++) { if (score >= 60) passCount++;}
โ Correct: cin should be written inside the for loop to get new input each time.
Mistake 2: if condition written incorrectly, filtering results wrong
For example, when filtering even numbers, if written as i%2 == 1:
// Error: i%2==1 is odd, will print odd numbersif (i % 2 == 1) { cout << i << " ";}
โ Correct: use i%2 == 0 to filter even numbers, and i%2 == 1 to filter odd numbers.
Mistake 3: Loop variable and input variable have the same name
For example, if both the loop variable and the input variable are named i:
// Error: duplicate variable names will cause confusion in the loopint i;cin >> i;for (int i = 1; i <= i; i++) { ... }
โ Correct: variable names should be distinct, for example, use i for the loop variable and n for the input variable.
6. ๐ข Next Lesson Preview: Detailed Explanation of while Loops (A New Way to Control Loops Flexibly)
In this lesson, we learned to use the combination of for, cin, and if to make loops “smart”, but the for loop has a characteristic – it must know the number of repetitions or range in advance (like from 1 to n, or looping 5 times). However, there are also scenarios where the “number of repetitions” is unknown:
- ๐ฎ Game: “Stop spawning monsters only when the player’s health reaches 0” (not knowing how many times to spawn, only knowing the stopping condition);
- ๐ฅค Buying drinks: “Stop buying when there is not enough money for one drink” (not knowing how many bottles to buy, only knowing the stopping condition).
At this point, the for loop is not sufficient; we need a new loop that “continues as long as the condition is met” – the while loop! In the next lesson, we will learn:
1. The syntax and execution principles of while loops;2. When to use while loops (differences from for loops);3. Practical cases of while loops (like “guessing a number game, until guessed correctly”).
Once you learn while loops, you will be able to solve more “uncertain repetition” problems. Looking forward to exploring together in the next lesson! ๐
