Loops Flashcards
What are the 4 kinds of loops we’ve learned?
while, do-while, for and for-each 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 do-while loop?
do {
body of the loop;
} while (testExpression)
What is the syntax of the for loop?
for (initialExpression; testExpression; updateExpression) {
//body of the loop;
}
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.
how would you loop through and print the numbers in this array?
int[] groupNumbers = {11, 27, 65, 82, 55};
for (int i = 0; i < groupNumbers.length; i++){
System.out.println(groupNumbers[i]);}
Or
For(num : groupNumbers) {
System.out.println(num);}
what will be the output of this for loop?
int number = 1;
for(int i = 1; i < =4; i++){
number *= i;
System.out.println(number);
1
2
6
24
when finding/comparing the length of an array for a for loop why do we use:
A. i < arrrayName.length
vs
B. 1 <= arrrayName.length
because indexing an array starts at the number 0, and so the last element in the array is actually located at the length - 1.
What is an iteration?
One time through the body of a loop.
A while loop runs until…….
A while loop runs until the test condition is made false.
What is the syntax for a while loop?
while (testExpression) {
//loop body
}
How does a while loop work?
1) It evaluates the boolean test expression:
a) If the value is false, the entire loop is skipped.
b) If the value is true, the the body of the loop is executed
and the loops starts over.