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);
}
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 whilej
is≥ 2
) - Update:
j -= 2
(Decrementj
by 2 each iteration) if (j % 5 == 0) continue;
- Skips printing if
j
is 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
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; }
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); }
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:
13