Skip to content
  • Open the math solver
  • Ask the AI tutor
  • Find an AP course
  • Create a quiz
  • Open the calculator
  • Graphing Calculator
  • Browse all calculators
  • Read math guides
↑ ↓Enter to open · Esc to close
Solve a problem
ProgrammingIntroduction to ProgrammingHigh school

Control Flow

Conditionals and loops; tracing code by hand.

Control flow is the order in which a program's statements run. By default, statements run top to bottom. Conditionals (`if`, `else if`, `else`) choose between branches based on a Boolean test, and loops (`for`, `while`) repeat a block until a condition changes.

Tracing code by hand, keeping a table of each variable's value after every step, is the most reliable way to predict what a program does and to find bugs. Most loop bugs are off-by-one errors at the boundaries or conditions that never become false, which create infinite loops.

Key ideas

  • A `for` loop suits a known number of repetitions; a `while` loop suits repeat-until-done.
  • Check boundary cases: zero iterations, one iteration and the last iteration.
  • Combine conditions with and, or and not; watch operator precedence.
  • Nested loops multiply: an outer loop of nn with an inner loop of mm runs nmnm times.

Worked example

What does this print? `total = 0; for i in 1..4: total = total + i * i; print(total)`

  1. i=1i = 1: total =1= 1.
  2. i=2i = 2: total =1+4=5= 1 + 4 = 5.
  3. i=3i = 3: total =5+9=14= 5 + 9 = 14.
  4. i=4i = 4: total =14+16=30= 14 + 16 = 30, which is printed.

Answer: 3030

Common mistakes

  • Off-by-one errors: using `<` where `<=` is needed or starting at 1 instead of 0.
  • Forgetting to update the loop variable in a `while` loop.
  • Using `=` (assignment) where `==` (comparison) is meant.

Practice questions

Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.

  1. 1.How many times does a loop from i=0i = 0 while i<10i < 10, step 2, run?

    Show answer

    55

  2. 2.A loop adds ii for i=1i = 1 to 1010. Final total?

    Show answer

    5555

  3. 3.An outer loop runs 6 times and an inner loop 4 times per outer pass. How many inner executions?

    Show answer

    2424

More in Introduction to Programming