The Gateway to Computer Science Excellence
+3 votes
2k views

What is the output of the following program?

Class Test
{ 
    public static void main (String [] args) 
    {  
        int x = 0; 
        int y = 0 
        for (int z = 0; z < 5; z++)
        { 
            if((++x >2)||(++y  > 2)) 
            {
                x++;
            }
        }
    System.out.printIn (x+ "" + y); 
    }
}
  1. 8 2
  2. 8 5
  3. 8 3
  4. 5 3
in Java by Boss (30.9k points) | 2k views
0

In a lot of programming languages (including C) in case there are two arguments (or operations), and the first one's result is sufficient to get the overall result; other argument is not processed.

This is called Short Circuit Evaluation, and it can be extended to any number of arguments.

Here, 

            if((++x >2)||(++y  > 2)) 

If the first operation is True, the second operation won't be evaluated.

 

Now read the answer by @rude.

1 Answer

+19 votes
Best answer

Before solving the questions, if we think why they asked this particular question then probability of getting correct answer increased. For example this question is an example of Short-Circuit Evaluation

Here is the Answer:

$z = 0$  : $x = 1$ and $y = 1$, Because $x++;$ will not be executed because condition is false

$z = 1$  : $x = 2$ and $y = 2$, Because $x++;$ will not be executed because condition is false

$z = 2$  : $x = 4$ and $y = 2$, Here $x++;$ will be executed, but $++y$ will not be executed due to short circuit evaluation

$z = 3$  : $x = 6$ and $y = 2$, Here $x++;$ will be executed, but $++y$ will not be executed due to short circuit evaluation

$z = 4$  : $x = 8$ and $y = 2$, Here $x++;$ will be executed, but $++y$ will not be executed due to short circuit evaluation

Hence at the end, It will print 8 2.

by Boss (35.7k points)
selected by
0
@arjun sir and @srestha please verify this.
0
how x value sudden increase from 2 to 4 ?
0

Because of pre-increment operator (++x ) Note: Value will be incremented before evaluation.

while z=2, x will be incremented by 1 in the if statement (++x >2) . Now, x value became 3. Then, again it will be incremented by 1 in inside of the if statement X++; so that x value suddenly incremented x=2 to x=4.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,390 answers
198,589 comments
105,443 users