Term 1: Lesson 18 - Tracing Code
Often on the AP exam they ask you to print out the first and last number printed by a loop. What are the first and last values printed by: int n = 5; while (n < 32) { n += 5; System.out.print (n + " "); }
10 35
Consider the following code: int a = scan.nextInt(); int b = scan.nextInt(); while (a < b) { a += b%a; System.out.println(a + " " + b); } What is output when the user enters 3 and 10?
4 10 6 10 10 10
What is output to the screen by the following code: int n = 3; while (n < 7) { n++; System.out.print (n + " "); }
4 5 6 7
What is output to the screen by the following code: int n = 10; while (5 < n) { n--; System.out.print (n + " "); }
9 8 7 6 5
Consider the following code: int a = 7; while (a < 15) { a += a % 4; System.out.print(a + " "); } What are the first and last numbers printed?
Infinite Loop
The word iteration means:
The process of doing something again and again.
tracing the loop
This means writing down what the loop does.
code tracing
the process of following the code in order of execution including what the value of any variables are. a useful practice for debugging; it is like pretending you're the compiler and writing down what the code would do. This is very important for evaluating code on paper.