Computer Applications
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);
Answer
Output of the above code is 12 and loop executes 2 times.
Working
This dry run explains the working of the loop.
| a | b | Remarks |
|---|---|---|
| 6 | 4 | 1st Iteration |
| 12 | 4 | 2nd Iteration |
In 2nd iteration, as a%b becomes 0 so break statement is executed and the loop exits. Program control comes to the println statement which prints the output as current value of a which is 12.
Related Questions
How many times will the following loop execute? Write the output of the code:
int x=10; while (true){ System.out.println(x++ * 2); if(x%3==0) break; }Rewrite the following do while program segment using for:
x = 10; y = 20; do { x++; y++; } while (x<=20); System.out.println(x * y );Write a program in Java to find the Fibonacci series within a range entered by the user.
Sample Input:
Enter the minimum value: 10
Enter the maximum value: 20Sample Output:
13To execute a loop 10 times, which of the following is correct?
- for (int i=11;i<=30;i+=2)
- for (int i=11;i<=30;i+=3)
- for (int i=11;i<20;i++)
- for (int i=11;i<=21;i++)