Chapter 5 Loops Flashcards
The do while loop definition
A do-while loop is the same as a while loop except that it executes the loop body first then checks the loop continuation condition.
This means that a do-while loop will always be executed at least once.
The do while loop syntax
do {
<statement(s)>
<update>
} while (<condition>);</condition></update>
Taking user input for do while loops
Scannerinput=newScanner(System.in);
intdata;
intsum=0;
do{
System.out.println(“Enteraninteger(enter0tostop)”);
data=input.nextInt();
sum+=data;
}while(data!=0);
System.out.println(“Thesumis”+sum);
How do you end do-while loop
The following while loop is wrong:
int i=0;
while (i < 10);
{
System.out.println(“i is “ + i);
i++;
}
In the case of the do-while loop, the following semicolon is needed to end the loop.
int i=0;
do {
System.out.println(“i is “ + i);
i++;
} while (i<10);
What does a for loop consist of
1) initialization section - is executed once at the start of the loop
2) continuation section - is evaluated before every loop iteration to check for loop termination
3) next iteration section - is evaluated after every loop iteration to update the loop counter
for loop syntax
for (<initialization>; <condition>; <update>) { <statement(s)>
}</update></condition></initialization>
Write a for loop that prints “Welcome to Java” 100 times
int i;
for (i = 0; i < 100; i++) {
System.out.println(“Welcome to Java!”);
}
An infinite loop is caused when?
loops conditions are incorrect.
for (int i = 0; i < 10; i–){ // Should have been i++
System.out.print(i + “, ”); // Infinite loop: 0, -1, -2, ..
}
int j = 0;
while (j < 10){
System.out.print(j + “, ”); // Infinite loop: 0,0,0,..
} // Forgot to change j in loop
How do you purposely create an infinite loop
To purposely create an infinite while loop, use the Boolean literal true as the condition.
If the condition in a for loop is omitted, it is implicitly true and will cause an infinite loop.
Nested loops definition
A loop can be nested inside another loop.
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is
repeated, the inner loops are reentered, and started anew.
Note: 1 microsecond is ____ of a second
one-millionth (10^(−6))
When do you use a break statement
You have used the keyword break in a switch statement. You can also use break in a loop to immediately terminate the loop.
When do you use a continue statement
You can also use the continue keyword in a loop. When it is encountered, it ends the current iteration and program control goes to the end of the loop body.