6 Iteration

AP Computer Science A Prep, 2024 - Rob Franek 2023

6 Iteration
Part V: Content Review for the AP Computer Science A Exam

THE while STATEMENT

When programmers want a statement (or multiple statements) to occur repeatedly, they have two options: (1) copy and paste the statement as many times as necessary (inefficient and ugly), or (2) write a conditional statement called a loop (efficient and “elegant”).

On the AP Exam, you will be expected to know two types of loops: while and for.

The syntax of a while loop is as follows:

while (condition) statement;

Note its similarity to the if statement. The while statement is a loop that does exactly what its name implies: the loop cycles again and again, while the condition is true. Consider a paint-soaked paintbrush that you just used to paint your bedroom. Hopefully, you will not store the paintbrush away until it is no longer dirty. A while loop that could represent this situation in pseudocode would look like:

1 while (paintbrush is dirty)

2 do not put away paintbrush;

3 put away paintbrush;

Note that if the condition is true (paintbrush is dirty), line 2 will continue to execute, over and over again, until the condition is false (paintbrush is not dirty). Once the condition is false, line 2 is skipped and line 3 is finally executed.

Unfortunately, this loop is fundamentally flawed. Although its logic seems to be correct, it is not. Within the statement(s) of a loop, the variable(s) in the condition must be modified so that there is a chance that the truth value of the condition will be changed. How will the paintbrush become less dirty—is this a self-cleaning paintbrush? Probably not. Therefore, the paintbrush will actually remain dirty, and Java will keep executing line 2, forever. When this happens, the programmer has written an infinite loop, which is a logical error and is therefore undesirable. Ever have your computer randomly “freeze” in the middle of your work, leaving it unresponsive and causing you to lose that perfectly sculpted digital picture that you just spent an hour perfecting? That is an infinite loop and definitely not desirable.

On the AP Exam, you must trace code in multiple-choice questions and detect infinite loops. In free-response questions, you must write code that is free of infinite loops.

While loops, like if statements, are therefore dependent on their conditions. If a condition is more intricate, as it usually is (Do we put the paintbrush away if it is not dirty, but it is wet? Not dirty but it is still not clean?), we can use the techniques outlined in the previous section. Boolean operators are mandatory and compound conditions and/or blocking are appropriate when necessary. A more realistic pseudocode representation of our paintbrush example could be

1 while (paintbrush is dirty && paintbrush is wet) // ! means NOT wet

2 {

3 clean paintbrush; // is it COMPLETELY clean?

4 dry paintbrush; // is it COMPLETELY dry?

5 do not put paintbrush away;

6 }

7 put paintbrush away;

In this example, the paintbrush will continue to be cleaned and dried (and not put away) until it is either NOT dirty or NOT wet, or both, at which point the condition will be false and the paintbrush will be put away. Remember that an && condition is true only if both conditions are true; therefore, if the paintbrush is not dirty but is still wet (or vice versa), it will be put away. Is this the desired result? Who cares?! Reading code is not about logical understanding of a situation; rather, it is about understanding the code and its result.

It is also worth noting here that an && statement may be short-circuited. Since both boolean statements on either side of the && must be true, a false result from the first statement will automatically render the condition false. As a result, Java will completely skip the second condition, bypassing the rest of the condition.

Image

1.Consider the following code segment.

int val1 = 2, val2 = 22, val3 = 78;

while (val2 % val1 == 0 || val2 % 3 == 0)

{

val3++;

val2--;

}

What will val3 contain after the code segment is executed?

(A) 77

(B) 78

(C) 79

(D) 80

(E) None of the above

Here’s How to Crack It

Tracing the loop is the best way to handle this type of problem. Remember that % returns the remainder of the division between the two numbers. In order for the condition to be true, there first must be no remainder when dividing val2 by val1. Since 22/2 = 11, there is no remainder, and the condition will be true (an “or” statement will be true if its first condition is true), and the loop statements will execute, incrementing val3 to 79 and decrementing val2 to 21. Since there are no visible statements that would decrement val3 below 79, we can eliminate (A) and (B). Execution then returns to the condition; this time, we have 21/2, which does yield a remainder, so we check the rest of the division, and 21 % 3 does not yield a remainder, so the condition is true overall and the loop statements execute again. We now have val3 = 80 and val2 = 20, eliminating (C). Again we try to evaluate the condition, which will be true since 20/2 has no remainder, increasing val3 to 81 and decreasing val2 to 19. We can now eliminate (D). By Process of Elimination, (E) is the answer.

When tracing loops, make a table of values for each variable to organize your work.

Image

THE for STATEMENT

A for statement is another type of loop. For loops and while loops are equally effective in controlling the flow of a program when a statement (or set of statements) is to be executed repeatedly. The syntax is quite different, however:

for (initializer; condition; incrementer) statement;

Image

Go Online!

For answers to test-prep questions for all your tests and additional test-taking tips, subscribe to our YouTube channel at www.youtube.com/ThePrincetonReview

Since the for loop requires more components, it can potentially avoid an infinite loop situation, although there is no guarantee. Let’s try a pseudocode example. Consider a younger sibling who is learning to count to 22. The child will start with 1 and continue counting until reaching 22, and then stop. The counting process repeats until the condition is met. Pseudocode may look like:

for (start with 1; not yet reached 22; go to the next number)

count the number;

The execution of a for loop is more difficult to understand. Here are the steps:

1. The initializer will occur first, beginning the process.

2. The condition will be checked to make sure it is true.

3. The statement(s) will execute.

4. The incrementer will occur, changing the number.

5. See step (1) and keep repeating (1) to (4), until (2) is false.

6. The loop ends.

A code example of this situation, outputting the current number to the screen, could be:

for (int num = 1; num <= 22; num++)

System.out.println(num);

This code will produce each counting number and output it to the screen, each on a separate line. Once again, remember that boolean operators are mandatory and compound conditions and/or blocking are appropriate when necessary.

Take Note: for loops and while loops are interchangeable, although one method may look more elegant than the other.

On the AP Exam, multiple-choice questions may show you several loop structures in both formats and ask you questions that compare the results, so you should practice working between them. On a free-response question that asks you to write a loop, you will be equally correct whether you decide to write a for loop or a while loop.

For and while statements are loops; if statements are not.

The following two code examples involving loops have identical results:

int num = 1;

while (num <= 3)

{

System.out.println(num);

num++;

}

System.out.println(“Done”);

---

for (int num = 1; num <= 3; num++)

System.out.println(num);

System.out.println(“Done”);

Each set of code is equally effective and equally respected in both the programming world and on the AP Exam. But multiple-choice questions can use either format, or both, so you should familiarize yourself with both.

While loops perform the blocked statement(s) once, and then evaluate the condition to determine whether the loop continues; for loops evaluate the condition first and then perform the blocked statement(s) if the condition is initially true.

Image

2.What will be the output when the following code is evaluated?

for (int k = 0; k < 3; k++)

{

for (int j = 1; j < 4; j++)

{

System.out.print(j + “ ”);

} System.out.println();

}

(A) 1 2 3 4

1 2 3 4

1 2 3 4

(B) 0 1 2

0 1 2

0 1 2

0 1 2

(C) 1 2 3

1 2 3

1 2 3

(D) 1 2 3

1 2 3

1 2 3

1 2 3

(E) 1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

Here’s How to Crack It

One glance at the condition in the outer for loop reveals that it will iterate a total of 3 times (k = 0, 1, and 2). The same will occur for the inner loop (j = 1, 2, and 3). Answers that involve loops of 4 can be eliminated, ruling out every choice except (C). There is no need to continue. However, to see why (C) works, work through the two loops. The outer loop sets k = 0, then j = 1. It prints 1 and a space and then increments j to 2. It prints 2 and a space and then increments j to 3. It prints 3 and a space and then increments j to 4. Since 4 is not less than 4, it terminates the inner loop. System.out.println() prints a line break. Then k is incremented to 1. Since k does not affect the output or the value of j, the loop again prints 1 2 3 before printing a line break. The value of k increments to 2, printing a third line of 1 2 3. Finally, k is incremented to 3, which terminates the outer loop, leaving (C) as the result of the print. The answer is (C).

Image

Image

3.Consider the following code fragments. Assume someNum has been correctly defined and initialized as a positive integer.

   I. int i;

for (i = 0; i < someNum; i++)

{

someNum--;

}

II. int i;

for (i = 1; i < someNum - 1; i++)

{

someNum -= 1;

}

III. int i = 0;

while (i < someNum)

{

i++;

someNum--;

}

All the following statements are true about these code fragments EXCEPT

(A) The for loops in I and II do not have the same number of iterations.

(B) The for loops in I and III have the same number of iterations.

(C) The value of someNum after the execution of I and III is the same.

(D) The value of i after the execution of II and III is the same.

(E) I, II, and III produce identical results in someNum.

Here’s How to Crack It

For an EXCEPT question, cross out the original question and rewrite it without the negative so that it’s easier to keep your task in mind. In this case, rewrite the question to say, “Which is false?”

The loops in I and III accomplish the same task. In each loop, i is initialized to 0, executes while i < someNum, then increments i by 1 and decrements someNum by 1 within the loop. Thus, any choice indicating the iterations or results of loops I and III are the same should be eliminated, because these conditions are true. Eliminate (B) and (C).

The loop in II will have fewer iterations than the loops in I and III (initializing i to 1 instead of 0, ending the loop when i < someNum — 1 instead of i < someNum). As a result, the loop in II will be executed fewer times. Choice (A), indicating that I and II do not have the same number of iterations, is true, so eliminate it.

For the remaining choices, let someNum equal a positive (nonzero) value (not too big)…let’s try 5.

I

i

SomeNum

0

5

1

4

2

3

3

2

II

i

SomeNum

SomeNum — 1

1

5

4

2

4

3

3

3

2

III

i

SomeNum

0

5

1

4

2

3

3

2

From these trace tables of values, you can see that the final value of i after the execution of II and III is 3, demonstrating that (D) is true. Eliminate (D). The value of someNum is only the same for I and III, so (E) is false, and is the correct choice.

Image

Image

4.Consider the following code segment:

for (int i = 1; i < 100; i = i * 2)

{

if (i / 50 == 0)

System.out.print(i + “ ”);

}

What is printed as a result of executing the code segment?

(A) 1 2 4 8 16 32 64

(B) 1 2 4 8 16 32

(C) 2 4 8 16 32 64

(D) 2 4 8 16 32

(E) 4 8 16 32 64

Here’s How to Crack It

The initial condition for execution to enter the loop is i = 1. Since 1/50 = 0 in integer division, 1 will be displayed, so eliminate (C), (D), and (E). The difference between (A) and (B) is the 64 at the end, so let’s skip the output in between and focus on the 64. If i = 64, the if statement will be false, and thus 64 will not be printed. Therefore, the answer is (B).

Image

Synopsis

Here’s a quick synopsis of which concepts from the chapters so far you can expect to find on the exam, and which you won’t.


Concepts Covered on the AP Computer Science A Exam

Concepts Not Covered on the AP Computer Science A Exam

Primitives

· int

· double

·  boolean

· short

· long

· byte

· char

· float

Increment/Decrement Operators

· x++

· x--

· ++x

· --x

Logical Operators

· ==

· !=

· <

· <=

· >

· >=

· &&

· ||

· !

· &

· |

· ^

· <<

· >>

· >>>

Conditional Statements

·  if/else

· for

· while

·  do/while

· switch

· plain and labeled break

·  continue

Miscellaneous


· ?: (ternary operator)

· User input

· JavaDoc comments

Image

Don’t Forget This!

Head over to your free online student tools to download a printable version of this chart and other important pages from within this book.

KEY TERMS

loop

while loop

infinite loop

short-circuited

for loop

Looking for More Help with Your APs?

We now offer specialized AP tutoring and course packages that guarantee a 4 or 5 on the AP. To see which courses are offered and available, visit www.princetonreview.com/college/ap-test-prep

CHAPTER 6 REVIEW DRILL

Answers to the review questions can be found in Chapter 13.

1.Consider the following output:

0 1

0 2 4

0 3 6 9

0 4 8 12 16

Which of the following code segments will produce this output?

(A) for (int x = 1; x < 5; x++)

{

for (int z = 0; z <= x; z++)

{

System.out.print(x * z + “ ”);

}

System.out.println(“ ”);

}

(B) for (int x = 1; x <= 5; x++)

{

for (int z = 0; z < x; z++)

{

System.out.print(x * z + “ ”);

}

System.out.println(“ ”);

}

(C) for (int x = 1; x < 5; x++)

{

for (int z = 0; z <= 4; z++)

{

System.out.print(x * z + “ ”);

}

System.out.println(“ ”);

}

(D) for (int x = 1; x < 5; x++)

{

for (int z = 0; z <= 4; z += 2)

{

System.out.print(x * z + “ ”);

}

System.out.println(“ ”);

}

(E) for (int x = 1; x <= 5; x++)

{

for (int z = 0; z <= x; z++)

{

System.out.print(x * z + “ ”);

}

System.out.println(“ ”);

}

2. The speed limit of a stretch of highway is 55 miles per hour (mph). The highway patrol issues speeding tickets to anyone caught going faster than 55 miles per hour. The fine for speeding is based on the following scale:

Speed

Fine

greater than 55 mph but less than 65 mph

$100

greater than or equal to 65 mph but less than 75 mph

$150

greater than or equal to 75 mph

$300

If the value of the int variable speed is the speed of a driver who was pulled over for going faster than 55 mph, which of the following code segments will assign the correct value to the int variable fine?

I.    if (speed >= 75)

fine = 300;

if (speed >= 65 && speed < 75)

fine = 150;

if (speed > 55 && speed < 65)

fine = 100;

II. if (speed >= 75)

fine = 300;

if (65 <= speed < 75)

fine = 150;

if (55 < speed < 65)

fine = 100;

III. if (speed >= 75)

fine = 300;

if (speed >= 65)

fine = 150;

if (speed > 55)

fine = 100;

(A) I only

(B) II only

(C) III only

(D) I and II

(E) I and III

3.Consider the following code segment:

int x = 10;

int y = 3;

boolean b = true;

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

{

x = x + y;

b = (x % y == 2);

if (!b)

{

y++;

i += 5;

}

}

What is the value of x after the code segment executes?

(A) 10

(B) 15

(C) 17

(D) 22

(E) 25

4.In the following statement, a and b are boolean variables:

boolean c = (a && b) || !(a || b);

Under what conditions will the value of c be true?

(A) Only when the value of a is different than the value of b

(B) Only when the value of a is the same as the value of b

(C) Only when a and b are both true

(D) Only when a and b are both false

(E) The value of c will be true for all values of a and b.

5.Consider the following code segment:

while ((x > y) || y >= z)

{

System.out.print(“*”);

}

In the code segment above, x, y, and z are variables of type int. Which of the following must be true after the code segment has executed?

(A) x > y || y >= z

(B) x <= y || y > z

(C) x > y && y >= z

(D) x < y && y <= z

(E) x <= y && y < z

6.Consider the following code segment:

int a = 0;

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

{

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

{

for (int z = 1; z <= 16; z = z * 2)

{

a++;

}

}

}

What is the value of a after the code segment executes?

(A) 31

(B) 180

(C) 200

(D) 300

(E) 400

7.Consider the following code segment:

int x = 10;

int y = x / 3;

int z = x % 2;

x++;

System.out.println(x)

What is printed as a result of executing the code segment above?

(A) 2

(B) 4

(C) 10

(D) 11

(E) 15

8.Consider the following code segment:

int a = 10;

double b = 3.7;

int c = 4;

int x = (int) (a + b);

double y = (double) a / c;

double z = (double) (a / c);

double w = x + y + z;

System.out.println(w);

What is printed as a result of evaluating the code above?

(A) 10

(B) 15

(C) 15.5

(D) 17

(E) 17.5

9.Consider the following code segments:

I.    int x = 10;

int y = 20;

int z = 0;

if (x < y && 10 < y/z)

{

System.out.println(“Homer”);

}

else

{

System.out.println(“Bart”);

}

II. int x = 10;

int y = 20;

int z = 0;

if (x > y && 10 < y/z)

System.out.println(“Homer”);

else

System.out.println(“Bart”);

III. int x = 10;

int y = 20;

int z = 0;

if (x < y || 10 < y/z)

System.out.println(“Homer”);

else

System.out.println(“Bart”);

Which of the code segments above will run without error?

(A) I only

(B) II only

(C) III only

(D) II and III

(E) I, II, and III

Summary

o While statements can be used to cause a command or series of commands to execute while a certain boolean statement is true.

o For statements are similar to while statements but include the initialization of a variable before the looping and a modification of the variable after each execution of the loop.