Unit 4: Iteration Flashcards Preview

AP CS-Applications > Unit 4: Iteration > Flashcards

Flashcards in Unit 4: Iteration Deck (7)
Loading flashcards...
1

What is the purpose of a while loop?

A while loop is used when you need to iterate for an indefinite period of time until a certain condition is met.

2

What is the purpose of a for loop?

A for loop is used when you need to iterate a specific number of times and you know how many times you must iterate.

3

What is the difference between a for loop and a for each loop?

A general for loop has to set up a variable to increment, a condition to follow, and the actual increment itself

A for each loop is more useful for arrays when the index is not needed

4

What is the correct way to create a for loop?
a) for(variable initialization, boolean expression, increment)

b) for(boolean expression; variable initialization; increment)

c) for(variable declaration : array name)

d) for(variable initialization; boolean expression; increment)

d) for(variable initialization; boolean expression; increment)

ex:
for(int i = 0; i < arr.length; i++)

5

What is a nested loop?

A loop exists inside the body of another loop

6

Consider the following output.
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
Which of the following code segments will produce this output?
(a) for (int j = 1; j <= 5; j++) {
for (int k = 1; k <= 5; k++) {
System.out.print(j + " ");
}
System.out.println();
}
(b) for (int j = 1; j <= 5; j++) {
for (int k = 1; k <= j; k++) {
System.out.print(j + " ");
}
System.out.println();
}
(c) for (int j = 1; j <= 5; j++) {
for (int k = 5; k >= 1; k--) {
System.out.print(j + " ");
}
System.out.println();
}
(d) for (int j = 1; j <= 5; j++) {
for (int k = 5; k >= j; k--) {
System.out.print(j + " ");
}
System.out.println();
}
(e) for (int j = 1; j <= 5; j++) {
for (int k = j; k <= 5; k++) {
System.out.print(k + " ");
}
System.out.println();
}

(D)

7

How often is the inner loop of a nested loop run?

a) Infinitely
b) One more time than the outer loop
c) Each time the outer loop runs
d) Two less times than the outer loop runs

c) Each time the outer loop runs