Skip to content
Now Accepting Applications for 2027-2028Apply
ITMagicITMagicAcademy
AP resources
APComputer ScienceCSA

Control Flow: Conditionals & Loops

AP Computer Science A — if/else conditionals, boolean operators, and for/while loops in Java. Worked example plus how to avoid off-by-one errors.

Control flow decides which statements run and how many times. In AP CSA (Java) this means conditionals and loops.

Conditionals

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C";
}

Boolean operators: && (and), || (or), ! (not). Comparison: ==, !=, <, >, <=, >=.

Loops

for loop — when you know how many times:

for (int i = 0; i < 5; i++) {
  System.out.println(i);   // prints 0,1,2,3,4
}

while loop — repeat while a condition holds:

int n = 1;
while (n <= 3) {
  n = n * 2;   // 2, then 4
}

Worked example

How many times does for (int i = 1; i &lt;= 5; i++) run? Exactly 5 times (i = 1,2,3,4,5).

Exam tip

Off-by-one errors are the number-one loop mistake. Check the boundary carefully: i &lt; 5 runs 5 times (0–4), but i &lt;= 5 runs 6 times (0–5). On free-response questions, trace the loop with a small table of variable values before writing your answer.

Interactive Simulation

Drag the sliders. See the change in real time.

for (int i = 0; i < 5; i++)

01234

runs 5 times

Short Lesson Video

The lesson video for this topic will be added soon.

Mock Exam

The mock exam for this topic will be added soon.

Practice Quiz

Test yourself: instant results and explanations.

  1. 1. How many times does for (int i = 0; i < 5; i++) run?

  2. 2. In Java, the && operator means:

  3. 3. How many times does for (int i = 0; i <= 5; i++) run?

Need support with this topic?

In a free 30-minute intro call we assess your level and build a study plan tailored to you.

Free intro call