циклы for
Введено| English | Значение |
|---|---|
| for loop/fɔː luːp/ | Цикл for |
A loop with a counter built in
- A for loop 计数循环 packs three parts into one line:
for (int i = 0; i < 5; i++) { ... }- Initialization (
int i = 0), condition (i < 5), update (i++). - Use
forwhen you know how many times to repeat.
The three parts, in order
- Initialization runs once, before the loop starts.
- The condition is checked before each pass (like
while). - The update runs after each pass, then the condition is re-checked.
- So the flow is: init → (test → body → update) → (test → body → update) → …

The three parts of a for loop and the order they run
for and while are interchangeable
- Any
forloop can be rewritten as awhileloop, and vice versa. for (int i=0; i<5; i++) {B}equalsint i=0; while (i<5) {B; i++;}.foris tidier when the counter setup, test, and change belong together.- Choose whichever makes the loop's intent clearest.
Counting a known number of times
for (int i = 0; i < n; i++)runs the body exactlyntimes (i=0ton-1).- Change the bounds to count differently:
i = 1; i <= nrunsntimes too. - Watch the boundary:
<stops one before,<=includes the end. - This is the standard pattern for "do something
ntimes."
Mind the loop bounds — an off-by-one changes the count. for (int i = 0; i < n; i++) runs n times (i from 0 to n-1); switching to i <= n runs n+1 times and often overruns an array. Trace the first and last value of i to confirm the count before trusting a for loop.
Printing 0,1,2,3,4:
for (int i = 0; i < 5; i++) { System.out.println(i); }istarts0, runs whilei < 5,i++each pass.- Prints
0 1 2 3 4(five values); ati = 5the condition fails → stop.
A for loop combines initialization (once), a condition (checked before each pass), and an update (after each pass): for (int i = 0; i < n; i++) runs the body n times. It's interchangeable with a while loop. Mind the bounds — < vs <= changes the count by one.
Цикл for, отсчитывающий от 0 до 4
i пробегает значения 0..4 (пять проходов); при i=5 условие не выполняется.
Три части заголовка цикла for идут в порядке...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
for (init; condition; update).
Сколько раз выполнится тело for (int i = 0; i < 5; i++)?
Сложность 2/5 · 140 монет + небольшой бонус за первое выполнение сегодня
i принимает значения 0,1,2,3,4 → 5 проходов.
Часть инициализации цикла for выполняется...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Init выполняется один раз; условие проверяется при каждом проходе; update выполняется после каждого.
Любой цикл for можно переписать как эквивалентный цикл while.
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
for и while взаимозаменяемы.
Сколько раз выполнится for (int i = 1; i <= 5; i++)?
Сложность 2/5 · 140 монет + небольшой бонус за первое выполнение сегодня
i принимает значения 1..5 (включительно) → 5 проходов.