AlgoViz

For loops

Easy

Repeat a known number of times

Problem

A for loop repeats a block a known number of times. It has three parts: initialisation, a condition checked before each pass, and an update after each pass.

In simple words

Repeat something a set number of times, like counting 1 to n.

The idea

A for loop bundles three things into one line: initialise a counter, test a condition before each pass, and update the counter after each pass. Use it when you know up front how many iterations you want — typically once per element of an array.

The trick

  • `for (int i = 0; i < n; i++)` visits every index exactly once; `<=` visits one too many.
  • The condition is checked before the first pass, so a loop can run zero times.
  • Nested loops multiply: a loop inside a loop over n elements is n² work.
0
i1
n5

Step 1 of 7. The counter starts at 1 and the loop runs while i ≤ 5. Values: —. i 1, n 5.

1/7
Optimal
timespace
1for (int i = 1; i <= n; i++) {2  // runs n times, i = 1, 2, ..., n3  print(i);4}

Input

array
[—]

Memory

i
1
n
5
printed

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
for i in 1..5: print(i)
Output:
1 2 3 4 5
Explanation:
Three parts: start at 1, keep going while i <= 5, add 1 each turn. Change any one and you change the sequence.

Example 2

Input:
sum = 0; for i in 1..5: sum += i
Output:
15
Explanation:
The loop body runs five times, and sum carries its value between turns rather than resetting.

Finished the walkthrough? Add it to your streak.