Loops — for Loop
I. In-Class Exercises
Programming Exercises
Sample Code
1// for loop drawing a regular 16-sided polygon
2#include "CTurtle.hpp"
3#include <bits/stdc++.h>
4using namespace std;
5using namespace cturtle;
6
7int main() {
8 // Create a canvas screen
9 TurtleScreen scr;
10 // Create a drawing turtle
11 Turtle turtle(scr);
12
13 int sides = 16;
14 int sideLength = 20;
15 double angle = 360.0 / sides;
16
17 for (int i = 0; i < sides; ++i) {
18 turtle.forward(sideLength);
19 turtle.right(angle);
20 }
21
22 // Pause the program
23 system("pause");
24 // End of program
25 return 0;
26}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int m, n;
5 cin >> m >> n;
6 int sum = 0;
7 for (int i = m; i <= n; ++i) {
8 if (i % 17 == 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 for (int chicken = 1; chicken <= 50; ++chicken) {
5 int rabbit = 50 - chicken;
6 if (chicken * 2 + rabbit * 4 == 160) {
7 cout << chicken << " " << rabbit << endl;
8 break;
9 }
10 }
11 return 0;
12}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int n;
5 cin >> n;
6 int sum1 = 0;
7 int sum2 = 0;
8 for (int i = 1; i <= n; i++) {
9 if (i % 2 == 0) {
10 sum1 += i;
11 } else {
12 sum2 += i;
13 }
14 }
15 cout << sum1 << " " << sum2 <<endl;
16 return 0;
17}II. Knowledge Summary
✨ for Loop Structure
What is a for Loop
In the previous lesson, we learned about while loops, where initialization, condition checking, and variable updating are scattered in different places. The for loop combines these three parts in a single line, making the structure more compact and especially suitable for scenarios where the number of iterations is known.
Syntax
for (①Initialize loop variable; ②Loop condition; ③Update loop variable) {
④Loop body
}Execution order inside a for loop:
- Execute ①Initialize loop variable (only once)
- Check if ②Loop condition is satisfied
- If true, execute ④Loop body
- Execute ③Update loop variable
- Repeat steps 2-4 until the condition is false
for Loop Flowchart
Notes
Keep the following points in mind when using for loops:
- A loop variable created inside a for loop cannot be used outside the loop
- If the for loop body has only one line of code, curly braces can be omitted (but beginners should always use them)
Comprehensive Example: Sum of Even Numbers from 1 to 100
Loop variable i starts at 2, increments by 2 each time, and accumulates into sum.
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
cout << sum << endl;Different for Loop Patterns
By modifying the three parts of a for loop (initialization, condition, update), different loop patterns can be achieved:
Ascending loop: Loop variable increases from small to large — the most common pattern.
int sum = 0;
for (int i = 1; i <= 100; ++i) {
sum += i;
}Descending loop: Loop variable decreases from large to small, useful when traversing from back to front.
int sum = 0;
for (int i = 100; i > 0; --i) {
sum += i;
}Step loop: Loop variable increases or decreases by a specified step value, useful for sampling at intervals.
int sum = 0;
for (int i = 1; i <= 100; i += 2) {
sum += i;
}✨ Loop Control Statements
break Statement: Terminate the Loop
The break statement is used to immediately exit the entire loop and execute the code after the loop.
1for (int i = 1; i <= 10; ++i) {
2 if (i % 7 == 0) {
3 cout << i << endl; // Output 7
4 break; // Exit loop immediately after finding it
5 }
6}continue Statement: Skip Current Iteration
The continue statement is used to skip the remaining code in the current iteration and proceed directly to the next iteration.
1for (int i = 1; i <= 10; ++i) {
2 if (i % 2 == 0) {
3 continue; // Skip even numbers
4 }
5 cout << i << " "; // Only outputs odd numbers: 1 3 5 7 9
6}✨ Variable Scope
What is Scope
Scope refers to the range within which a variable can be used. A variable can only be used within the curly brace block where it was created; it cannot be accessed outside that block. Understanding scope helps avoid many common programming errors.
Local Variables
Variables created inside curly braces are called local variables and can only be used within those braces.
for (int i = 0; i < 5; ++i) {
int x = i * 2; // x is only valid inside the loop
}
// cout << x; // Error! x cannot be used here
// cout << i; // Error! i cannot be used here eitherIf there are variables with the same name inside and outside curly braces, they are two independent variables that don't affect each other:
1int a = 10;
2{
3 int a = 20; // This is a new variable, unrelated to the outer a
4 cout << a << endl; // Output 20
5}
6cout << a << endl; // Output 10, the outer a was not changedHowever, if the inner block doesn't redefine a same-name variable but modifies it directly, it will affect the outer variable:
int a = 10;
{
a = 20; // No int keyword, not defining a new variable, but modifying the outer a
}
cout << a << endl; // Output 20, the outer a was changedGlobal Variables
Variables created outside the main function are called global variables and can be used anywhere in the file.
1#include <bits/stdc++.h>
2using namespace std;
3
4int count = 0; // Global variable, accessible by all functions
5
6int main() {
7 count = 10;
8 cout << count << endl; // Output 10
9 return 0;
10}Note: Global variables are generally not recommended because they can be modified anywhere, making code difficult to maintain and debug.
III. Homework
Programming Exercises
- Factorial Using Loops: L1124
- Count of Integers: L1125
- Calculate 2 to the Power of n: L1126
- Count Possible Rectangles: L1127