A loop inside an if block
A loop written inside an if branch only runs when that branch's condition is true. If the condition is false, the loop is skipped. An else branch can hold a loop too.
Understanding A loop inside an if block in Years 7–8 Creating Digital Solutions
What it does: When x is 0 or less, the condition is false, so the for loop never starts and nothing prints. 2 > 0 is true, so the loop runs. It counts from 1 to x, which is 2, so it prints 1 and then 2. The loop must sit inside the if block so the condition controls it. In the second option the loop is outside the if, so it always runs. 0 > 0 is false, so the else branch runs. The loop in the else branch repeats 3 times.
Common mistakes: The loop counter is i, not j. The variable j was never created, so the loop inside the if block can't print it. It should be print i. A for loop needs the word to between the start and end values. The loop inside the if block should read for i from 1 to 3.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 3–47) and word search (Modules 3–125).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
if x > 0 then for i from 1 to xFill in the Blanks
Spot the Error
Student with a class code? Join your class →