+ 1

Can someone explain this program??

Decision Making in C++ 24 Switch Statement Example If alpha input is 6 , what will be alpha value after processing cin>>alpha; if(a>0) switch (alpha) { case 1: alpha = alpha + 3; case 3: alpha++; break; case 6: alpha = alpha + 6; case 8: alpha = alpha * 8; default: alpha--; } else alpha=alpha+2;

6th Dec 2023, 8:13 AM
Haram Abbas Lar
Haram Abbas Lar - avatar
10 Answers
+ 2
Zoya a switch is different from a loop. There is no increment, it will run only once. The switch will skip straight to the "case" which matches the input and execute whatever is there, then it will stop
6th Dec 2023, 9:28 AM
StuartH
StuartH - avatar
+ 2
Do you mean what it the user gives another number other than 6? If so then the switch will jump to the case which matches that input. As the code has errors (which is the point of the question as you're meant to spot them) it will be unpredictable what happens but it will jump to whatever "case" value matches the input given. If it does not match any, it will jump to "default".
7th Dec 2023, 12:41 PM
StuartH
StuartH - avatar
+ 1
In switch if any case miss break statement then next case will also be execute So here if alpha is 6 so in case 6: alpha will be 12 but there is no break in this case so case 8: will be execute so alpha will now be 12 * 8 = 96 But also there is no break in case 8: so default will be execute now alpha will be 95
6th Dec 2023, 9:14 AM
A͢J
A͢J - avatar
+ 1
introduction to C++ course will help you!
7th Dec 2023, 4:19 PM
Alhaaz
Alhaaz - avatar
0
How can we know that what number we have to increment
6th Dec 2023, 9:15 AM
Haram Abbas Lar
Haram Abbas Lar - avatar
0
Increment where?
6th Dec 2023, 9:16 AM
A͢J
A͢J - avatar
0
/* 0 and negative numbers will get +2. positive numbers after 8, it will be 1 less than alpha... */ #include <iostream> using namespace std; void test(int alpha){ if(alpha>0) switch (alpha) { case 1: alpha = alpha + 3; case 3: alpha++; break; case 6: alpha = alpha + 6; case 8: alpha = alpha * 8; default: alpha--; } else alpha=alpha+2; cout<<alpha<<endl; } int main() { int n; cin>>n; test(n); for(int i=-10;i<100;i++){ cout << "alpha = " << i << ' '; test(i); } }
6th Dec 2023, 10:28 AM
Bob_Li
Bob_Li - avatar
0
As in case 1: alpha=alpha+3; Similarly in case 3: alpha++; and in case 6:alpha= alpha+6; I'm asking about how it is solved
7th Dec 2023, 1:11 AM
Haram Abbas Lar
Haram Abbas Lar - avatar
0
If a user give another number then what will we do
7th Dec 2023, 1:37 AM
Haram Abbas Lar
Haram Abbas Lar - avatar
0
that is why we have to put it in a function if we want to reuse the switch case.
7th Dec 2023, 1:38 AM
Bob_Li
Bob_Li - avatar