Menu
Topics Index
...
`

For loop output558


If you need explanation Read this topic

If you need Answer Take test on this topic

For loop output558
What will the output of the following program?
public class ForTest
{
    public static void main(String[] args)
    {
        for (int i = 1; i <= 10; i++)
        {
            if (i % 2 == 0) continue;
            if (i == 9) break;
            System.out.println(100 + i);
        }
    }
}

A. 1001
1003
1005
1007
1009
B. 101
103
105
107
C. 1001
1003
1005
1007

D. Compilation Error
E. Goes into infinite loop
Topic: Java for loops vs Java while loops vs Java do while loops

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Answer is B...
The continue statement skips the current iteration of a for, while , or do-while loop.
break statement leaves a loop.
coming to the program,
when i = 1,both if conditions fail and 100 + i = 100 + 1 =101 is printed
(1001 is not prnted because 100 and i are both integers and so '+' does an addition rather than concatenation)
when i = 2,statemnts below the continue in for loop are skipped
when i = 3,both if conditions fail and 100 + i = 100 + 3 =103 is printed
when i = 4,statemnts below the continue in for loop are skipped
when i = 5,both if conditions fail and 100 + i = 100 + 5 =105 is printed
when i = 6,statemnts below the continue in for loop are skipped
when i = 7,both if conditions fail and 100 + i = 100 + 7 =107 is printed
when i = 8,statemnts below the continue in for loop are skipped
when i = 9,second if (i==9) is true and loop is terminated

Posted by Shashanka Mogaliraju    2015-03-16 03:53:01


ANS is B

Concept of continue and break keyword is used.

For loop runs from 1 to 10.for each even number loop continues and when it reaches to 9 then loop will be broken.

--when I=1
If condii fails then 100+1=101 will get printed.

When I=2,if condition is evaluated to be try then for loop statements after continue will be skipped.

OUTPUT:
101
103
105
107

Posted by Mânïshå Mùlchåndânï    2015-03-16 17:15:15


Output will be
101
103
105
107
  coz it will start next l
Iteration when it hits the condition i%2==0 that is even numbers for odds other than 9 will print their output

Posted by Mohd Ajsam    2015-03-16 17:30:15


This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Shashanka Mogaliraju,  for 'Best Comment' and Shashanka Mogaliraju for the 'Popular Comment'. The 'lucky liker' is Srikar Mogaliraju. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-03-19 07:23:47


© meritcampus 2019

All Rights Reserved.

Open In App