Can anyone please explain the logic of this switch statement problem which outputs 3? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 13

Can anyone please explain the logic of this switch statement problem which outputs 3?

int a=2; int x=0; switch (a){ case 1: ++x; case 2: ++x; case 3: ++x; default: ++x; } s.o.p (x);

11th Oct 2017, 8:49 AM
Panda Lad
Panda Lad - avatar
9 Answers
+ 8
You didnt use any break statements, which results in the program executing all following statements after case 2, including those who actually dont match. Include break statements after each case and output will be 1.
11th Oct 2017, 8:59 AM
Shadow
Shadow - avatar
+ 6
oh okay ...absence of break statement... thank you Naitomea and shobhit ☺
11th Oct 2017, 9:02 AM
Panda Lad
Panda Lad - avatar
+ 6
😊okay , give it a try though... don't worry its for learning ... I am challenging with different levels just to learn ....i believe we'll learn more with question...✌
15th Nov 2017, 9:41 AM
Panda Lad
Panda Lad - avatar
+ 5
it is because you are missing break statement so on case 2 when a is 2 it also implements logic of case 3 as you are missing break statement.
11th Oct 2017, 8:59 AM
shobhit
shobhit - avatar
+ 3
@vitalij I meant s.o.p for " System.out.print"
11th Nov 2017, 4:33 AM
Panda Lad
Panda Lad - avatar
+ 2
what is means s.o.p?
11th Nov 2017, 12:26 AM
Vitalij Bredun ♡ Python Petersburg
Vitalij Bredun ♡ Python Petersburg - avatar
0
Should his one not be 7 since it is the last statement?
11th Nov 2017, 1:07 PM
ambrozote
ambrozote - avatar
0
i cant learn anythinf from this app can someone help me pls😅
15th Jan 2018, 2:40 PM
Nei Topulli
Nei Topulli - avatar
0
thanx Jigme but how can i learn more fast
15th Jan 2018, 2:44 PM
Nei Topulli
Nei Topulli - avatar