ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.7

while Loops

Skill 2.ASkill 3.ASkill 4.B

Big idea: A while loop repeats its body as long as its condition is true, checking before every pass. Use it when you don't know in advance how many times to repeat.

Learning objectives
  • Identify when an iterative process is required to achieve a desired result.
  • Develop code to represent iterative processes using while loops and determine the result of these processes.

How a while loop runs

  • Check the condition. If false, skip the loop entirely.
  • Run the body.
  • Go back to step 1.
Code
int n = 1;
while (n < 50) {
  n *= 3;
  System.out.print(n + " ");
}
System.out.println();
System.out.println("final " + n);
Output
3 9 27 81
final 81

Loops that run zero times, or forever

If the condition starts false, the body never runs. If nothing in the body moves the condition toward false, the loop is infinite.

Code
int k = 10;
while (k < 5) {
  System.out.println("never");
}
System.out.println("skipped");
// int j = 0;
// while (j < 5) { System.out.println(j); }   // infinite: j never changes
Output
skipped

Sentinel and digit loops

A classic while loop processes the digits of a number until none are left.

Code
int num = 4071;
int sum = 0;
int digits = 0;
while (num > 0) {
  sum += num % 10;
  num /= 10;
  digits++;
}
System.out.println(sum + " " + digits);
Output
12 4
Key points
  • Iteration repeats code zero or more times while a condition is true.
  • The condition is checked before every pass, including the first.
  • An infinite loop happens when the condition never becomes false.
  • An off-by-one error runs the loop one time too many or too few.
Watch out
  • Make sure the body changes something the condition depends on.
Exam tip
  • Trace loops with a table: one row per pass, one column per variable, plus a column for the condition.
Quick check
How many times does the body run?
int x = 100;
while (x > 1) {
  x /= 2;
}
Show answer
6 times: 50, 25, 12, 6, 3, 1.