+ 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;
10 ответов
+ 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
+ 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".
+ 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
+ 1
introduction to C++ course will help you!
0
How can we know that what number we have to increment
0
Increment where?
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);
}
}
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
0
If a user give another number then what will we do
0
that is why we have to put it in a function if we want to reuse the switch case.