Question

I found an interesting Programing question :

What will be the values of a,b,c,f after executing this programe ?

int i=0,a=0,b=0,c=0,f=0;
while(i<=5){
switch(i++){
    case 1:++a;
    case 2:++b;
    break;
    case 3:
    case 4:++c;a++;b++;
    break;
    default:++f;
}
}

I thought that the values

a=2 , b=2 , c=2 and f=2 but

when i executed this programe i got a = 3, b = 4, c = 2 and f = 2.

I understood how c and f got it values 2 but how come a=3 and b=4.

(As per the syntax ++a and a++ are different as ++a updates the value and then uses it where as a++ uses the value and then updates it )

Can anyone explain how a and b got its values as 3 and 4.

UPDATE:

Hey my doubt is : In i++ the intial value is 0 and not 1. But then how case 4 => a=3

It should be a=2 and should incriment the value if there was any updation of 'a' in case 5 (which is not true)as i haven't given any substitution like a=a++.

Any Help appreciated.

Was it helpful?

Solution

I suggest you to do this exercise with paper and pen. Anyway:

  1. i = 0 ==> f =1;
  2. i = 1 ==> a = 1; b = 1; (ther isn't break after case 1!)
  3. i = 2 ==> b = 2;
  4. i = 3 ==> c = 1; a = 2; b = 3;
  5. i = 4 ==> c = 2; a = 3; b = 4;
  6. i = 5 ==> f = 2;

OTHER TIPS

Hope this will help you...

When i is 0 
    None of the case matched and went to default
    so a=0,b=0,c=0,f=1;

When i is 1 
    Case 1 and 2 will execute as there is no break after 1;
    so a=1,b=1,c=0,f=1;

When i is 2 
    Case 2 will execute
    so a=1,b=2,c=0,f=1; 

When i is 3 
    Case 3 and 4 will execute as there is no break after 3;
    so a=2,b=3,c=1,f=1; 

When i is 4 
    Case 4 will execute
    so a=3,b=4,c=2,f=1; 

When i is 5 
    Default will execute
    so a=3,b=4,c=2,f=2;

Remember that switch statements support "fall through" - for i=2, only b is incremented, but for i=1 both are incremented.

the pre and post increment ( ++a, and a++ ) are best explained in this previous answer

Update As pointed out in the comments bellow there is a fundamental difference in the C++ and Java implementation of those concepts. But here is a simple example in java

        x = 1;
        y = ++x;  Here y = 2 and x =2 because we first increment x and assign it to y

        x = 1;
        y = x++;  But here y = 1 and x = 2 because we first assign x to y and then increment x

in essense , y = x++ is equivalent to those 2 statements
            y =x;
            x = x + 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top