How does this switch work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How does this switch work?

https://code.sololearn.com/c897RteP88N2/?ref=app Why does it return 25 and not 250? Is it because it executes case(10), and so why, since current x's value is 25?

25th Aug 2020, 8:06 PM
Samuele Artico
Samuele Artico - avatar
8 Answers
+ 3
x = 5 switch(x) { case(2):x=x*2; break; case(5):x=x*5; case(10):x=x*10; break; default:x=0; } Samuele Artico its working how it suppose to work. x=5 so it goes to case 5 where x = 5*5=25 Next since there is no break statement it continue with the next proceeding case that is case 10 where x = 25 * 10 = 250 Next since there is a break statement now its break and we are left with x = 250
25th Aug 2020, 8:11 PM
Rohit
+ 2
Samuele Artico check and run this code and try to understand. give a special attention to break; #include <iostream> using namespace std; int main() { int x = 5; switch(x){ case 2: cout << "hello" << endl; case 5: cout << "s" << endl; case 7: cout << "a" << endl; case 21: cout << "m" << endl; case 222: cout << "u" << endl; case 2616: cout << "e" << endl; case 9372: cout << "l" << endl; break; case 273737: cout << "m" << endl; case 2368737: cout << "u" << endl; } return 0; }
25th Aug 2020, 8:30 PM
Rohit
0
Ok, but sholdn't it control if x=10 since case(10) is still present?
25th Aug 2020, 8:15 PM
Samuele Artico
Samuele Artico - avatar
0
but what about case(10)
25th Aug 2020, 8:18 PM
Samuele Artico
Samuele Artico - avatar
0
But case(10) means that it should control if x=10 and ONLY if that's true execute the code that follows, like all other cases do. Then why doesn't it check if x value is egual to 10 before executing x=x*10?
25th Aug 2020, 8:25 PM
Samuele Artico
Samuele Artico - avatar
0
I perfectly know what break does, but since the code goes on after case(5), it should however see if x=10 before executing case(10). Don't u think so?
25th Aug 2020, 8:37 PM
Samuele Artico
Samuele Artico - avatar
0
coffeeunderrun thank u!!
25th Aug 2020, 8:37 PM
Samuele Artico
Samuele Artico - avatar
0
Switch stament is used at the place of else if statement to avoid repeating of else if statement. We declare conditions in switch using case As the program runs, the conditions are checked and if false , next condition is taken for checking. It's good to put break after each case and default at last for getting output when no condition is true.
26th Aug 2020, 11:24 AM
Siddharth bore