Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

3.2: While Loops

A while loop can run zero times. Identify a changing quantity that eventually makes the condition false.

College Board Unit 2

How it works

A while loop checks its condition before each iteration and keeps running until that condition becomes false. Unlike a for loop, nothing updates the control variable automatically, so the body must change it. While loops fit situations where the number of iterations is not known in advance, such as processing digits of a number or reading until a sentinel value appears.

Check that every path through the body moves the condition toward becoming false.

Common error

An update placed inside a conditional branch that does not always execute.

Worked example

Java

int n = 507;
int digits = 0;
while (n > 0) {
    digits++;
    n /= 10;
}
System.out.println(digits);

Output

3

The values at the condition are 507, 50, 5, and 0. Only the first three enter the body.

Exercises

3.2.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int n = 3;
while (n < 20) n *= 2;
System.out.println(n);
Show solution

Output

24

The updates produce 6, 12, and 24; the condition is checked again after each update.

3.2.2 · Write code

Write public static int digitSum(int n) for n >= 0. Return the sum of its decimal digits, including a return value of 0 for input 0.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

Check your code

Java

System.out.println(digitSum(0));
System.out.println(digitSum(508));

Expected output

0
13
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic