Computer Applications
How many times will the following loop execute? Write the output of the code:
int a = 5;
while (a > 0) {
System.out.println(a-- + 2);
if (a % 3 == 0)
break;
}
Answer
Loop executes two times.
Output
7
6
Reason — Let's go through the Java program step by step to understand how it works:
Initial Value:
a = 5
Iteration 1:
System.out.println(a-- + 2);
a--
: Post-decrement is used, so the current value ofa
(5
) is used first, then decremented.- Output:
5 + 2 = 7
a
becomes4
if (a % 3 == 0)
:4 % 3 = 1
→ Condition is false, so the loop continues.
Iteration 2:
System.out.println(a-- + 2);
a--
: Current value ofa
(4
) is used, then decremented.- Output:
4 + 2 = 6
a
becomes3
.
if (a % 3 == 0)
:3 % 3 = 0
→ Condition is true, so thebreak
statement exits the loop.
Therefore, the loop executes 2 times and the output is:
7
6
Related Questions
To execute a loop 5 times, which of the following is correct?
Define a class to accept a number and check whether it is an FDS Number or not. A number is called an FDS Number if the sum of the factorials of its digits equals the number itself.
Example 1:
Input: 145
Output: FDS Number [1! + 4! + 5! = 1 + 24 + 120 = 145]Example 2:
Input: 123
Output: Not an FDS Number [1! + 2! + 3! = 1 + 2 + 6 ≠ 123]import java.util.Scanner; class KboatFDSNum { static int fact(int d) { int f = 1; _______(1)_________ { _______(2)_________ } _______(3)_________ } public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); int num = in.nextInt(); int t = num, sum = 0; _______(4)_________ { _______(5)_________ _______(6)_________ _______(7)_________ } _______(8)_________ { _______(9)_________ } else { _______(10)_________ } } }
Convert the following for loop segment to an exit-controlled loop.
for (int x = 1, y = 2; x < 11; x += 2, y += 2) { System.out.println(x + "\t" + y); }
Rewrite the following do while program segment using for:
x = 10; y = 20; do { x++; y++; } while (x<=20); System.out.println(x * y );