Courses / Computer Science I
Programming I

Loops and Repeated Computation

Computer Science I 244 words Free to read

Doing It Again

A loop repeats a block of code. The staple forms are the while loop and the for loop.

A while loop runs as long as a condition stays true, checking it before each pass. Correct execution requires three ingredients:

IngredientRole in CodeExample
InitializationSets start pointi = 0
ConditionDecides when to stopi < 5
UpdateMoves toward falsei = i + 1

Forget the update, and you get an infinite loop that freezes the program by running forever.

A for loop handles known repetitions or steps through collections. For example, range(n)range(n) produces values starting at 0 and stopping before nn:

range(n):0,1,,n1\text{range}(n): 0, 1, \ldots, n-1

Control and Pitfalls

The for loop convention stops before nn, a frequent source of the off-by-one error where a loop runs one time too many or too few because a boundary like < versus <= is wrong.

Two control statements adjust loops internally:

StatementWhat It Does
breakExits the loop immediately
continueSkips to the next iteration

Loops can also nest, placing one inside another. If an outer loop runs nn times and an inner loop runs mm times, the inner body executes n×mn \times m times, directly impacting performance.

Loops and Repeated Computation

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes

Programming I