368 views
9 9 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int x = 3, y = 1;

    switch (x - 1) {
        case 1:
            y = y + 2;
        case 2:
            y = y * 3;
        case 3:
            y = y - 1;
            break;
        default:
            y = y + 5;
    }

    printf("%d", y);
    return 0;
}

3 Answers

4 4 votes

Here, $\texttt{x = 3}$.

So, $\texttt{x - 1 = 2}$.

Therefore, execution starts from $\texttt{case 2}$.

Initially, $\texttt{y = 1}$.

In $\texttt{case 2}$, $\texttt{y = y * 3}$, so $\texttt{y = 1 * 3 = 3}$.

There is no $\texttt{break}$ after $\texttt{case 2}$, so execution falls through to $\texttt{case 3}$.

In $\texttt{case 3}$, $\texttt{y = y - 1}$, so $\texttt{y = 3 - 1 = 2}$.

Now $\texttt{break}$ is encountered, so the switch ends.

Therefore, the output is $\texttt{2}$.

0 0 votes

here x=3,

x-1=2

switch(2) 

execution starts from case 2 

y = y * 3;  // y=3

hence y=3

because of no break condition after case 2 it falls through to case 3 

  1. y = y - 1;  // y=2
  2. break;  // break condition encountered switch ends here 

therefore the output is 2

Answer:
Position:
Show:

Related questions

7 7 votes
2 2 answers
282
282 views
GO Classes asked Jun 5
282 views
What is the output of the following code?#include <stdio.h int main() { int i, j, count = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (i == j) continue; i...
10 10 votes
2 2 answers
407
407 views
GO Classes asked Jun 5
407 views
What is the output of the following code?#include <stdio.h int main() { int a = 10, b = 20; int *p, *q; p = &a; q = &b; *p = *p + 5; *q = *p + *q; p = q; *p = *p - 10; pr...
4 4 votes
2 2 answers
318
318 views
GO Classes asked Jun 5
318 views
What is the output of the following code?#include <stdio.h int update(int x) { x = x + 3; return x * 2; } int main() { int a = 4, b; b = update(a); printf("%d %d", a, b);...
6 6 votes
2 2 answers
346
346 views
GO Classes asked Jun 5
346 views
What is the output of the following code?#include <stdio.h int main() { int a[5] = {2, 4, 1, 3, 5}; int i, sum = 0; for (i = 0; i < 5; i++) { if (a[i] % 2 == 0) sum = sum...