Computer Applications
How many times will the following loop execute? Write the output of the code:
for(int j = 12; j >= 2; j -= 2) {
if(j % 5 == 0)
continue;
System.out.println(j);
}
Java Iterative Stmts
1 Like
Answer
Loop executes six times.
Output
12
8
6
4
2
Reason
Step 1: Understanding the Loop
- Initialization:
j = 12 - Condition:
j >= 2(Loop runs whilejis≥ 2) - Update:
j -= 2(Decrementjby 2 each iteration) if (j % 5 == 0) continue;- Skips printing if
jis divisible by5.
Step 2: Iterations Breakdown
| Iteration | Value of j | Condition j % 5 == 0 | Action |
|---|---|---|---|
| 1st | 12 | Not divisible by 5 | Print 12 |
| 2nd | 10 | Divisible by 5 | Skip (continue) |
| 3rd | 8 | Not divisible by 5 | Print 8 |
| 4th | 6 | Not divisible by 5 | Print 6 |
| 5th | 4 | Not divisible by 5 | Print 4 |
| 6th | 2 | Not divisible by 5 | Print 2 |
Step 3: Final Output
12
8
6
4
2
Answered By
3 Likes
Related Questions
Give the output of the following program segment. How many times is the loop executed?
for(x=10; x>20;x++) System.out.println(x); System.out.println(x*2);Define a class to accept a number and check whether it is a SUPERSPY number or not. A number is called SUPERSPY if the sum of the digits equals the number of the digits.
Example1:
Input: 1021 output: SUPERSPY number [SUM OF THE DIGITS = 1+0+2+1 = 4, NUMBER OF DIGITS = 4 ]Example2:
Input: 125 output: Not an SUPERSPY number [1+2+5 is not equal to 3]Define a class to accept a number from user and check if it is an EvenPal number or not.
(The number is said to be EvenPal number when number is palindrome number (a number is palindrome if it is equal to its reverse) and sum of its digits is an even number.)
Example: 121 – is a palindrome number
Sum of the digits – 1+2+1 = 4 which is an even number