What will be the output of the following code snippet?1234567891011121314151617#include <stdio.h> int main() { int x = 20; switch (x) { case 10: if (x == 10) printf("Ten "); case 20: if (x == 20) printf("Twenty "); case 30: printf("Thirty "); default: printf("Other "); } return 0; }
Question
What will be the output of the following code snippet?1234567891011121314151617#include <stdio.h> int main() { int x = 20; switch (x) { case 10: if (x == 10) printf("Ten "); case 20: if (x == 20) printf("Twenty "); case 30: printf("Thirty "); default: printf("Other "); } return 0; }
Solution
The output of the code will be "Twenty Thirty Other ".
Here's the step by step explanation:
-
The variable
xis initialized with the value 20. -
The
switchstatement checks the value ofx. -
Since
xis 20, it matches with thecase 20:. So, it enters this case. -
Inside
case 20:, there is anifstatement that checks ifxis 20. Sincexis indeed 20, it prints "Twenty ". -
After executing the code inside
case 20:, it does not encounter abreakstatement. So, it continues to execute the code in the next case, which iscase 30:. It prints "Thirty ". -
Again, it does not encounter a
breakstatement, so it continues to execute the code in thedefault:case. It prints "Other ". -
The program ends with a return statement
return 0;.
So, the final output is "Twenty Thirty Other ".
Note: The break statement is used to terminate the execution of the nearest enclosing loop or conditional statement in which it appears. Without a break statement, the program continues to execute the next case in the switch statement, even if the case does not match the switch expression.
Similar Questions
What will be the output of the following code snippet?
What is the output for the following code?
What will be the output of the following program?1234567891011121314151617181920#include <stdio.h>void one();void two();void one() { for(int i = 0; i < 2; i++){ two(); }}void two() { printf("TWO ");}int main(){ one(); two(); return 0;}
What will be the output of the following code snippet?123456789101112131415#include <stdio.h> int main() { char direction = 'N'; if (direction == 'N') printf("North"); else if (direction == 'S') printf("South"); else if (direction == 'E') printf("East"); else if (direction == 'W') printf("West"); else printf("Unknown"); return 0; }
What will be the output of the following code snippet?1234567891011121314151617#include <stdio.h> int main() { int x = 20; switch (x) { case 10: if (x == 10) printf("Ten "); case 20: if (x == 20) printf("Twenty "); case 30: printf("Thirty "); default: printf("Other "); } return 0; }
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.