Chapter 4 - Loops Flashcards
What are the 3 kinds of loops?
while, do-while, and for loops
What is the loop body?
The loop body is the statements inside the loop that are executed every iteration
What is the difference between a while loop and a do-while loop?
A while loop checks the loop-continuation-condition before entering the loop body, while a do-while loop checks it after the first iteration
When are while and do-while loops generally used?
When the number of iterations is not predetermined
When is a for loop generally used?
When the loop body needs to be executed a certain number of times
What is the syntax of the while loop?
while (loop-continuation-condition) {
Statement(s);
}
What is the syntax of the do-while loop?
do {
Statement(s);
} while (loop-continuation-condition)
What is the syntax of the for loop?
for (initial-action; loop-continuation-condition; action-after-each-iteration) {
Statement(s);
}
Analyze the following statement:
double sum = 0;
for (double d = 0; d
D. The program compiles and runs fine.
Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + … + 99/100?
A:
double sum = 0;
for (int i = 1; i
E. CD
The following loop displays _____.
for (int i = 1; i );
i++;
}
A. 1 2 3 4 5 6 7 8 9 B. 1 2 3 4 5 6 7 8 9 10 C. 1 2 3 4 5 D. 1 3 5 7 9 E. 2 4 6 8 10
D. 1 3 5 7 9
Do the following two statements in (I) and (II) result in the same value in sum?
(I):
for (int i = 0; i<10; i++) {
sum += i;
}
Yes
What is i after the following for loop?
int y = 0;
for (int i = 0; i<10; ++i) {
y += i;
}
A. 9
B. 10
C. 11
D. undefined
D. undefined
Explanation: The scope of i is inside the loop. After the loop, i is not defined.
Given the following four patterns,
Pattern A 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6
Pattern B 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Pattern C 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 6 5 4 3 2 1
Pattern D 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Which of the pattern is produced by the following code? for (int i = 1; i = 1; j--) System.out.print(j ); System.out.println(); }
C
Analyze the following fragment:
double sum = 0; double d = 0; while (d != 10.0) { d += 0.1; sum += sum + d; }
A. The program does not compile because sum and d are declared double, but assigned with integer value 0.
B. The program never stops because d is always 0.1 inside the loop.
C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers.
D. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + … + 1.9
C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers.