info@meritcampus.com    +91-85006-22255
...
`

Break example output
What will be the output of the following program?
`class BreakExample{    public static void main(String s[])    {        int sum = 0;        for(int i = 2; i <= 10; i+=2 )        {            if( i == 8 ) break;            sum += i;        }        System.out.println("sum = " + sum);    }}`

 A. sum = 18 B. sum = 36 C. Compilation error D. sum = 12
Topic:

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

Here we have the concept of Break which is used tk exit from a loop. By using break, you can force immediate termination of a loop even though there are iterations to be completed. break can also be used inside while loop. break can also be used inside nested loops (loop inside loop).

Coming to program, Here we have initialized sum to 0. In the next step we used for loop in which i value is 2 and condition i<=10 which satisfies. i value is is incremented by 2. And in if condition i==8 executes every iteration until it becomes true. Then we got break statement which helps to terminate from loop. sum += i the i value is 8 and 4 will be added in during iteration. Result will be stored in sum and control goes to print method and prints the output as sum = 12.

Posted by Sai Ram    2014-12-22 09:53:50

ANS IS D

"Break" Keyword is used which do not execute statements after it and move the control out of the loop.

for Loop starts with counter i=2 and increased by 2 i+=2 it runs till i<10

i=2
sum=sum+i=0+2=2
i=4
sum=sum+i=2+4=6
i=6
sum=sum+i=6+6=12
i=8
break;sum=sum+i will not execute and control will go out of the loop and sum will get printed which is 12.

Sum=12

Posted by Mânïshå Mùlchåndânï    2014-12-22 10:32:24

This dose is now closed and the winners are Sai Ram,  for 'First Correct Comment', Sai Ram, Mânïshå Mùlchåndânï,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Shashanka 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    2014-12-23 04:09:33