OutputHard2 marks
Give the output of the following program segment and also mention the number of times the loop is executed: int a, b; for(a = 6, b = 4; a <= 24; a = a + 6) { if(a % b == 0) break; } System.out.println(a);
Topic: The break statement
Previous-year question practice database
Answer
Exam answer
12
The loop is executed 2 times.
Explanation
break leaves the loop ENTIRELY, unlike continue which only skips the rest of the current pass. Dry-run it, with b fixed at 4: Pass 1: a = 6, and 6 % 4 = 2, not 0, so the loop continues; a becomes 12 Pass 2: a = 12, and 12 % 4 = 0, so break fires and the loop ends a is left at 12, which the println outside the loop displays. Both parts of the question matter: the value printed is 12, and the loop executed 2 times. Note that a retains the value it held when break fired — the update a = a + 6 does not run again.
More from Revision Tour II
Read the if program segment given below:
if(a > b)
z = 25;
else
z = 35;
Which one of the following is the correct conversion of the if program segment to ternary?2026The earth spins on its axis completing one rotation in a day. The earth revolves around the sun in 365 days to complete one revolution. What is the Java concept depicted in the given picture?2026Rewrite the following program segment using a for loop.
int a = 5, b = 10;
while(b > 0)
{
b -= 2;
}
System.out.println(a * b);2026Users must be above 10 years to open a self-operated bank account. Write this logic using a ternary operator and store the result (the eligibility message) in a String variable named idStatus and print it.2026Give the output of the following program segment and mention how many times the loop is executed.
int K = 1;
do
{
K += 2;
System.out.println(K);
} while(K <= 6);2026Write a program to accept a number and check if it is a Mark number or not. A number is said to be Mark when the sum of the squares of each digit is an even number as well as the last digit of the sum and the last digit of the number given is the same.
Example: n = 246
sum = 2 x 2 + 4 x 4 + 6 x 6 = 56
56 is an even number as well as last digit is 6 for both sum as well as the number.2026