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.
- 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.
int n = 1;
while (n < 50) {
n *= 3;
System.out.print(n + " ");
}
System.out.println();
System.out.println("final " + n);Output3 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.
Codeint 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 changesOutputskippedSentinel and digit loops
A classic while loop processes the digits of a number until none are left.
Codeint num = 4071;
int sum = 0;
int digits = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
digits++;
}
System.out.println(sum + " " + digits);Output12 4- 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.
- Make sure the body changes something the condition depends on.
- Trace loops with a table: one row per pass, one column per variable, plus a column for the condition.
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.