حلقة for
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
In the last lesson you met the three parts of a loop and read a first for loop. This lesson makes you fluent: you will write counting loops that go up, go down, and step by more than one, and you will learn to trace a loop by hand, which is the fastest way to find a bug.
The track picture continues. The for loop is the track with a lap counter printed on the starting line: the start, the finish check, and the counter update are all written together in one place, in the parentheses. That makes for the natural choice when you know how many laps to run.
Why this matters: in the backend, "do something N times" and "do something for each number in a range" are everyday needs, and a clear for loop is the way to say it.
This lesson builds on BEG-013-L01 and on += and ++ from BEG-010.
Learning Objectives
By the end of this lesson you will be able to:
- Write a
forloop with the shapefor (start; condition; update) { body }. - Count up, count down, and step by a value other than one.
- Choose between
<and<=to get the exact count you want. - Trace a loop with a table of variable values.
- State the scope of a loop variable declared in the
forheader. - Use a loop to accumulate a sum or a repeated calculation.
Written Explanation
The shape
for (int i = 1; i <= 5; i++) {
// body
}| Slot | Example | When it runs |
|---|---|---|
| Start | int i = 1 | Once, before anything else |
| Condition | i <= 5 | Before every iteration, including the first |
| Update | i++ | After every iteration, before the next check |
The two semicolons inside the parentheses separate the three slots. The Java Tutorials call the slots initialization, termination expression, and increment; this course says start, condition, update.
Counting up and down
- Up by one:
for (int i = 1; i <= 5; i++)gives 1, 2, 3, 4, 5. - Down by one:
for (int i = 5; i >= 1; i--)gives 5, 4, 3, 2, 1. Notice that the condition flips from<=to>=: when counting down you keep going whileiis still at least the last value. - By a step:
for (int i = 0; i <= 10; i += 2)gives 0, 2, 4, 6, 8, 10.
The update can be any statement that changes the counter: i++, i--, i += 3, even i *= 2.
The count: < versus <=
Two loops that look alike produce different counts:
| Loop | Values of i | Runs |
|---|---|---|
for (int i = 1; i <= 5; i++) | 1, 2, 3, 4, 5 | 5 |
for (int i = 0; i < 5; i++) | 0, 1, 2, 3, 4 | 5 |
for (int i = 1; i < 5; i++) | 1, 2, 3, 4 | 4 |
A handy rule: with a start a and an end b, a loop with i <= b runs b - a + 1 times, and with i < b it runs b - a times (when step is 1). Programmers often count from 0 with <, because "0 up to but not including n" runs exactly n times. You will see that pattern constantly.
Tracing a loop
To trace, make a table with a column for each variable and a row for each iteration. Here is the sum of 1 to 5:
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}| Check | i | Condition i <= 5 | sum after body |
|---|---|---|---|
| 1 | 1 | true | 1 |
| 2 | 2 | true | 3 |
| 3 | 3 | true | 6 |
| 4 | 4 | true | 10 |
| 5 | 5 | true | 15 |
| 6 | 6 | false | loop ends |
The last row is important: i becomes 6 and the check fails. In every counting loop, the counter finishes past the last value. That is why, after the loop, i is not 5.
The scope of the loop variable
A variable declared in the for header, such as int i, exists only inside the loop. The Java Tutorials say its scope runs from the declaration to the end of the block the for governs. After the closing brace, i is gone, and using it is a compile error. This is a feature: the counter cannot leak into later code. If you need the final value after the loop, declare the variable before it:
int i;
for (i = 1; i <= 5; i++) { }
// i is 6 herePrefer the usual form unless you really need the value afterwards.
Do not touch the counter in the body
The update slot is the loop's place for changing the counter. If you also change i inside the body, the loop skips values or never ends, and the code is hard to read. We return to this in L06.
Examples
Example 1: sum of 1 to 5 with a trace (simple)
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
System.out.println("i=" + i + " sum=" + sum);
}Output:
i=1 sum=1
i=2 sum=3
i=3 sum=6
i=4 sum=10
i=5 sum=15This printed trace matches the table above. Printing the counter and the accumulator inside the body is a quick way to check any loop.
Example 2: counting down by 3 (practical)
for (int i = 10; i >= 1; i -= 3) {
System.out.print(i + " ");
}
System.out.println();Output:
10 7 4 1 The values are 10, 7, 4, 1. The next would be -2, which fails i >= 1, so the loop ends. System.out.print (without ln) keeps the values on one line.
Example 3: growing a balance (realistic)
A savings account earns 5 percent a year, added to the balance each year. This loop shows the balance for three years (an illustration of the idea, not financial advice):
double balance = 1000;
for (int year = 1; year <= 3; year++) {
balance = balance * 1.05;
System.out.printf("Year %d: %.2f%n", year, balance);
}Output:
Year 1: 1050.00
Year 2: 1102.50
Year 3: 1157.63Each iteration uses the result of the one before it: the balance is both read and written. The format codes come from BEG-011-L04: %d for an integer, %.2f for two decimal places, %n for a new line.
Backend Insight
Counting loops appear wherever a program deals with ranges: page numbers (pages 1 to N of search results), retry attempts (try up to 3 times), batches (process 100 items at a time), and time windows. A few habits pay off immediately:
- Name the end value.
for (int attempt = 1; attempt <= maxAttempts; attempt++)documents itself;<= 3does not. - Keep the body short. If the body grows long, move it into a method (you will learn those soon) and call it.
- Know the count before running. If you can say "this runs
ntimes", you can also reason about its cost, which is the start of the complexity work in BEG-039.
Common Mistakes
Mistake 1: Using < when you meant <=
- Incorrect:
for (int i = 1; i < 10; i++)when you wanted 1 to 10. It stops at 9. - Correct:
for (int i = 1; i <= 10; i++).
Always ask: "Is the last value included?"
Mistake 2: A condition that does not match the direction
for (int i = 10; i <= 1; i--) { }The condition 10 <= 1 is false immediately, so the body never runs. When counting down, use >=.
Mistake 3: A semicolon after the header
for (int i = 1; i <= 3; i++);
{
System.out.println("Hello");
}The ; is an empty body. The loop spins three times doing nothing, then Hello prints once. Never put a semicolon after the closing parenthesis.
Mistake 4: Using the loop variable after the loop
i is out of scope after the closing brace, so the compiler reports a "cannot find symbol" style error. Declare it before the loop if you need it.
Mistake 5: Changing the counter in the body
Adding i++ in the body of a loop that already has i++ in the header makes the counter jump by two. Use one place for the update.
Exercises
Try each exercise yourself before opening the solutions.
Level A: Foundation
A1. List the values of i: for (int i = 2; i <= 10; i += 4).
أظهر الحل A1
A1. 2, 6, 10. The next value would be 14, which fails the condition.
A2. How many times does for (int i = 0; i < 7; i++) run? How many for i <= 7?
أظهر الحل A2
A2. 7 times (values 0 to 6) and 8 times (values 0 to 7).
A3. Write the header of a loop that counts from 20 down to 5 in steps of 5.
أظهر الحل A3
A3. for (int i = 20; i >= 5; i -= 5), giving 20, 15, 10, 5.
Level B: Application
B1. Write a loop that computes the sum of the even numbers from 2 to 20 and prints the result.
أظهر الحل B1
B1.
int sum = 0;
for (int i = 2; i <= 20; i += 2) {
sum += i;
}
System.out.println(sum); // 110B2. Complete the trace table for this loop: int p = 1; for (int i = 1; i <= 4; i++) { p *= 2; }. Give i and p after each iteration, and the final p.
أظهر الحل B2
B2. After iteration 1: i=1, p=2; 2: i=2, p=4; 3: i=3, p=8; 4: i=4, p=16. Final p is 16 (the loop computes 2 to the power 4).
B3. The loop below should print 1 to 5 but prints nothing. Fix it.
for (int i = 1; i > 5; i++) {
System.out.println(i);
}أظهر الحل B3
B3. The condition i > 5 is false at the start. Use i <= 5.
Level C: Challenge
C1. Print the first 10 values of a savings plan: start with 100, add 20 each month, and print the total after each month.
أظهر الحل C1
C1.
int total = 100;
for (int month = 1; month <= 10; month++) {
total += 20;
System.out.println("Month " + month + ": " + total);
}C2. Without running it, say what this prints and why:
for (int i = 0; i < 6; i++) {
System.out.print(i + " ");
i++;
}أظهر الحل C2
C2. It prints 0 2 4 . The header adds 1 and the body adds another 1, so i goes 0, 2, 4, 6 and the check 6 < 6 fails. This is the "counter changed in two places" mistake.
Mini Challenge
Write a program that prints a multiplication table for one number. Store the number in an int variable (for example 7). The loop must print lines like 7 x 1 = 7 up to 7 x 10 = 70.
Then change the loop so that it prints only the lines for odd multipliers (1, 3, 5, 7, 9) by changing the update, not by adding an if.
Check your work: the first version prints 10 lines, the second prints 5, and changing the number variable changes every line.
Summary & Next Lesson
Key takeaways
- A
forloop has the shapefor (start; condition; update) { body }; use it when the count is known. i++,i--, andi += nare the common updates; the condition must match the direction.<=includes the last value,<excludes it. Starting at 0 with<runs exactlyntimes.- Trace a loop with a table; the counter ends past the last value.
- A variable declared in the header lives only inside the loop.
Next lesson
The next lesson, "while and do-while", covers loops where you do not know the count in advance, such as asking until the input is valid.
Self-check
- In which order do start, condition, and update run?
- How many times does
for (int i = 3; i <= 8; i++)run? - What condition do you use to count down to 1?
- Why does
for (...);with a semicolon before the braces cause trouble? - What is the value of
ithat makesfor (int i = 1; i <= 5; i++)stop?
أظهر الإجابات
- Start once; then condition, body, update; then condition again.
- 6 times (3, 4, 5, 6, 7, 8).
i >= 1.- The semicolon is an empty body, so the loop does nothing and the braces run once afterwards.
- 6, the first value for which
i <= 5is false.
References
- Oracle, The for Statement (Java Tutorials). It supports the three expressions, the descending and
i++examples, and the scope of a variable declared in the initialization. - Oracle, Java Language Specification, SE 21, Chapter 14. It supports the order in which the start, condition, body, and update run. The trace tables and the
<versus<=counts were checked by compiling and running the examples with JDK 21.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.