NEW
Font size
WorksheetsRepetition Control Structures
Total questions: 50
Worksheet time: 18mins
Which statement best defines looping in programming as presented: it repeats a program or a section of a program, replacing each repetition with new data, and continues while a specified condition is met?
Executing a program once with constant input values
Repeating a program or section with new data while a condition is satisfied
Randomly selecting different code paths on each run
Compiling code multiple times to optimize performance
Which statement about loops is emphasized: loops can execute a block of code as long as a specified condition is reached and substitute new data for each repetition?
Loops always execute exactly once regardless of conditions
Loops run only when input data never changes
Loops execute repeatedly while a condition is satisfied and use new data each time
Loops require manual restarting after each pass
What is the primary purpose of a counter in a program loop?
To randomize loop entries for testing
To keep track of the number of times a program segment is repeated
To store user credentials during iteration
To convert boolean conditions into integers
Before execution of counting in a loop, what should be done to all counters?
Set them to null to avoid overflow
Initialize them (usually to zero) before the loop executes
Multiply them by the loop limit to save time
Declare them as constants to prevent changes
Which statement describes how a predetermined number of passes relates to program termination?
A program cannot terminate based on loop passes
After completing a predetermined number of passes, the program may then be terminated
Termination happens only when the counter overflows
Programs must always ask the user to stop the loop
During the Initialization step in a control loop, where is the counter value set and to what typical value?
Inside the loop; typically set to the loop limit
Outside the loop; typically set to zero or one
Inside the loop; typically set to a random value
Outside the loop; typically left uninitialized
In the Test for Limit Conditions step, when is the loop-terminating condition checked according to the description?
Only in the middle of the loop body
At either the beginning or the end of a loop
After the loop has fully completed
Only when an exception occurs
What happens during Incrementation/Decrementation in a control loop?
The loop condition is replaced with a constant value
One is added or subtracted after each loop so the counter reflects the number of operations performed
The program resets the counter to zero each time
The loop skips directly to termination
Which loop type in Java tests the condition before executing the loop body and repeats while the condition is true?
do...while loop
for-each (enhanced for) loop
while loop
recursive method
Which Java loop type tests its condition at the end of the loop body, allowing the body to execute at least once?
while loop
do...while loop
enhanced for-each loop
switch loop
According to the table, which loop executes a sequence of statements multiple times and abbreviates code that manages the loop variable?
while
do...while
for
try-catch
Which control statement terminates a loop or switch and transfers execution to the statement immediately following it?
continue
break
return from main
throw
What is the effect of the continue statement in a loop as described?
Ends the current loop entirely and moves on
Skips the remainder of the loop body and immediately retests the condition
Pauses the loop and waits for user input
Reinitializes the loop counter to zero
You need a loop that ensures the body executes at least once even if the condition is false initially, and you also need to count iterations starting from zero set outside the loop and increment each pass. Which combination best matches these requirements?
while loop with counter initialized inside and decremented each pass
do...while loop with counter initialized outside and incremented after each iteration
for loop with no counter and condition checked only at the start
recursive calls with no explicit condition check
In Java, what is the primary purpose of a while loop?
To execute a block exactly once regardless of conditions
To repeat a statement or block while a given boolean expression remains true
To iterate a fixed number of times predetermined at compile time
To declare a condition without executing any statements
Select the correct Java syntax template for a while loop that executes one or more statements while a condition holds.
while condition do { statements }
while (boolean_expression) { statement1; statement2; }
do { statement1; } until (boolean_expression)
repeat (boolean_expression) -> { statements; }
According to the description, when do the statements inside a while loop execute?
Only once before the condition is checked
As long as the boolean expression evaluates to true
Only after the loop completes all iterations
When the boolean expression evaluates to false
Based on the described mechanism, what happens immediately after the statements inside a while loop execute?
The loop exits unconditionally
The test expression is evaluated again
The boolean expression is inverted for the next check
The loop counter resets to its initial value
Refer to the flowchart of the while loop. What is the decision made at the diamond-shaped node labeled Test Expression?
Whether to initialize the loop variable
Whether the condition is true to enter/continue the loop body or false to exit
Which of several cases to select using a switch statement
Whether to print the current value before incrementing
Consider the Java code:
int num = 1;
while (num <= 5) {
System.out.println("Line " + num);
++num; }
What is the last value printed and why does the loop stop?
Line 5; after printing 5, num becomes 6, making num <= 5 false
Line 6; the loop prints after incrementing to 6 and then stops
Line 4; the loop stops before reaching the boundary value
Line 5; the loop stops because ++num prevents the print from executing on the last iteration
If the increment statement in the example were moved above the println, which output would result? Assume the code becomes:
int num = 1;
while (num <= 5) {
++num;
System.out.println("Line " + num); }
Line 1 to Line 5 (unchanged)
Line 2 to Line 6 (six lines printed)
Line 2 to Line 6 (five lines printed)
Line 1 to Line 4 (four lines printed)
In Java, consider:
int sum = 0, i = 5;
while (i != 0) {
sum += i; --i;
}
System.out.println("Sum = " + sum);
What value is printed for sum?
5
10
15
20
Given the snippet:
int i = 4;
while (i > 0) {
System.out.print(i);
i--; }
What is the output and why does the loop terminate?
1234 because i increases to reach 4
4321 because i starts at 4 and is decremented until i becomes 0
43210 because the loop includes 0 before stopping
3210 because printing starts after the first decrement
In the code
int i = 4;
while (i > 0) {
System.out.print(i);
/* missing i--; */ }
what behavior occurs?
The loop runs exactly four times
The program throws a compile-time error
An infinite loop occurs because i never changes and the condition stays true
The loop runs once due to automatic decrement
A countdown program reads an integer n and executes:
while (n > 0) {
System.out.print(n + "," );
--n; }
System.out.print("Fire!");
If the user enters 4, what is the exact console output?
4,3,2,1,Fire!
4 3 2 1 Fire!
4,3,2,1, Fire! (with a space before Fire!)
3,2,1,0,Fire!
In the countdown example, when does the loop body execute?
Only when n is equal to 0
While the condition n > 0 remains true
Exactly n times regardless of n's value
Until the user presses Enter
In the Java snippet: while (n<5) { System.out.print("Enter the score: "); score = scan.nextInt(); sum = score + sum; n++; } Which variable controls the loop termination, and what change makes the loop eventually stop?
score controls the loop; entering 0 stops it automatically
n controls the loop; incrementing n each iteration leads to n reaching 5
sum controls the loop; it stops when sum exceeds 5
average controls the loop; assigning average = sum/5 ends the loop
Given the console interaction shown:
Enter the score: 1, 3, 5, 6, 3.
The program then prints The Average is: 3.6.
Which expression in the code computes this value?
average = sum/5;
average = sum/n; with n equal to the number of inputs
average = (score + sum)/n;
average = sum/3;
In the example using JOptionPane, what input will cause the while loop to terminate? The condition is:
while (Integer.parseInt(jop.showInputDialog("Type non-zero digit to accept and zero to stop")) != 0) {
continue;
}
Any non-zero digit, because continue exits the loop
The digit 0, because the condition becomes false
A negative number only, because parseInt rejects zero
Cancel button, because parseInt returns -1
Which statement about continue in Example 5 is accurate?
continue immediately ends the loop and moves to the code after the loop
continue skips the current iteration and re-evaluates the while condition
continue converts the user input to zero
continue displays the 'Bye' message dialog
After the GUI loop in the example ends, which actions occur according to the code?
The program prints the average of all inputs and then exits.
A message dialog saying "Bye" is shown, then System.exit(0) terminates the program.
Inputs are written to a file and the window closes automatically.
The loop restarts because System.exit(0) returns control to main.
Which statement best describes a unique characteristic of the do-while loop compared to the while loop?
The condition is checked before any statements execute, so the body may never run.
The loop body executes at least once before the condition is evaluated.
It can only iterate a fixed number of times determined at compile time.
It requires multiple conditions to continue looping.
According to the explanation, what happens first in a do-while loop’s execution cycle?
The test expression is evaluated and, if true, the body executes.
The body executes once, then the test expression is checked.
Both the test expression and one statement execute simultaneously.
The loop checks for a false condition before running the body.
Refer to the flowchart of the do-while loop. After the body executes, the flow proceeds to the decision node labeled Test Expression. If the outcome is True, what occurs next?
Control exits the loop immediately.
The body of the do-while loop executes again.
The condition is ignored and the program terminates.
The loop converts into a while loop automatically.
In the provided Java example, which input value causes the loop to terminate?
Any negative value
A non-integer numeric value
The value 0.0
The largest value entered so far
In the Java example, what is the role of the statement sum += number; placed inside the do block?
It resets the sum to zero before each iteration.
It adds the current input number to the running total.
It checks whether the user entered 0 to stop the loop.
It converts the input to an integer before summing.
A programmer wants to ensure that a prompt for user input displays at least once, even when the test condition is initially false. Based on the material, which loop structure should be chosen and why?
Use a while loop because it evaluates the condition before the first execution.
Use a do-while loop because it executes the body once before testing the condition.
Use a for loop because it has initialization, condition, and update in one line.
Use recursion because it always runs the base case before any checks.
Given the Java do-while snippet for squaring numbers:
int y, x = 1, total = 0;
do {
y = x * x;
System.out.println(y + total);
total += y;
++x; }
while (x <= 5);
What is the final value printed by System.out.print("Total is " + total); after the loop finishes?
25
30
55
60
In the square-sum program that prints 1, 5, 14, 30, 55 and then "Total is 55", what does the intermediate line 14 represent?
The cube of 3
The running total after adding 32
The square of 4
The number of iterations left
Consider this guidance: "The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, where the user input within the block is what is used to determine if the loop has to end." Which scenario best matches this usage?
Iterating over a fixed array of 10 items
Repeating a menu until the user types 0 to quit
Running a loop exactly five times using a counter
Processing a file until end-of-file using a for loop
In the password-checking program, the code uses pass.equalsIgnoreCase("jru"). What is the effect of equalsIgnoreCase here?
It trims whitespace before comparing
It compares strings while ignoring letter case differences
It accepts any substring that contains "jru"
It converts the input to lowercase permanently
Study the password program structure: a Scanner reads a username, then in a do-while loop it asks for a password up to three attempts. If the password matches, it prints "accepted" and calls System.exit(0). What happens if the user never enters the correct password within three attempts?
The program loops forever asking for passwords
The program throws a compile-time error
The loop ends after three tries and the program continues past the loop
The program restarts and asks for the username again
Which output demonstrates that equalsIgnoreCase accepts both lowercase and uppercase forms of the same password?
Enter Password: jru → accepted, Enter Password: JRU → accepted
Enter Password: PUP → invalid, Enter Password: ceu → invalid
Enter Password: upLB → invalid only
Enter Password: jru → invalid each time
According to the coding guidelines, which is a common mistake when writing a do-while loop?
Placing the condition before the loop body
Using break instead of continue
Forgetting the semicolon after the while(condition)
Declaring loop variables outside the method
Based on the guideline "make sure that your do-while loops will terminate at some point," which change best ensures termination in a user-prompt loop?
Remove any input checks so the loop always executes
Add a counter limit or a sentinel input such as 0 to exit
Replace do-while with while(true)
Use System.exit(0) in every iteration
In the number-entry example preceding the square-sum, the loop keeps prompting "Enter a number:" and then prints the running sum, stopping when the user enters 0. Which control pattern is being used to stop the loop?
Counter-controlled loop with fixed iterations
Flag-controlled loop without input
Sentinel-controlled loop using 0 as the sentinel
Exception-controlled loop using try-catch
In the Java snippet for computing a power, which variable is initialized to 1 so that repeated multiplication produces the correct result of base^exp inside the while loop?
base
exp
power
counter
Given the power program: base and exp are read via JOptionPane, power starts at 1, counter starts at 0, and while(counter < exp){ power = power * base; counter++; }. If base = 3 and exp = 4, what value is displayed for power?
9
12
27
81
In the vowel/consonant counting program, which control structure checks each character of the input string to classify it as a vowel or consonant?
An if-else chain outside the loop
A switch statement inside a while loop
A for-each loop over characters
A do-while loop with nested if statements
According to the vowel/consonant program, which set of characters is treated as vowels during the switch classification?
a, e, i, o, u in lowercase only
A, E, I, O, U in uppercase only
Both lowercase and uppercase a, e, i, o, u
All letters except y
