Computer Applications
Give the output of following code and mention how many times the loop will execute?
int i;
for( i=5; i>=1; i--)
{
if(i%2 == 1)
continue;
System.out.print(i+" ");
}
Java
Java Iterative Stmts
ICSE 2019
68 Likes
Answer
Output of the above code is:
4 2
Loop executes 5 times. The below table shows the dry run of the loop:
i | Output | Remark |
---|---|---|
5 | 1st Iteration — As i % 2 gives 1 so condition is true and continue statement is executed. Nothing is printed in this iteration. | |
4 | 4 | 2nd Iteration — i % 2 is 0 so condition is false. Print statement prints 4 (current value of i) in this iteration. |
3 | 4 | 3rd Iteration — i % 2 is 1 so continue statement is executed and nothing is printed in this iteration. |
2 | 4 2 | 4th Iteration — i % 2 is 0. Print statement prints 2 (current value of i) in this iteration. |
1 | 4 2 | 5th Iteration — i % 2 is 1 so continue statement is executed and nothing is printed in this iteration. |
0 | 4 2 | As condition of loop (i >= 1) becomes false so loops exits and 6th iteration does not happen. |
Answered By
28 Likes
Related Questions
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 numberWrite a program to input a number and find whether the number is an emirp number or not. A number is said to be emirp if the original number and the reversed number both are prime numbers.
For example, 17 is an emirp number as 17 and its reverse 71 are both prime numbers.
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); }
To 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++)