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?
9 Antworten
+ 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
+ 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;
}
0
Ok, but sholdn't it control if x=10 since case(10) is still present?
0
but what about case(10)
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?
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?
0
coffeeunderrun thank u!!
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.