switch statement in c 2b 2b

Solutions on MaxInterview for switch statement in c 2b 2b by the best coders in the world

showing results for - "switch statement in c 2b 2b"
Lennart
02 Sep 2019
1switch(expression) {
2  case x:
3    // code block
4    break;
5  case y:
6    // code block
7    break;
8  default:
9    // code block
10}
Cain
06 Oct 2016
1switch (n)
2{
3    case 1: // code to be executed if n = 1;
4        break;
5    case 2: // code to be executed if n = 2;
6        break;
7    default: // code to be executed if n doesn't match any cases
8}
Roberta
20 Jul 2018
1switch(expression) {
2   case 1:
3      //equivalent to if(expression == 1){//do someting...}
4      //do something...
5      break; 
6    //if case 1 is true the rest of the statments arn't 
7    //evaluated because of the break
8   case 45:
9      //equivalent to else if(expression == 45){//do someting...}
10      //do something...
11      break;
12    
13   // you can have any number of case statements and default has to be last
14   default :
15      // equivalent to else{//do someting...}
16      //do something...
17}
18
19switch(expression) {
20   case 1:
21      //equivalent to if(expression == 1){//do someting...}
22      //do something...
23   case 45:
24      //equivalent to if(expression == 45){//do someting...}
25      //do something...
26   default :
27      //always runs if there are no breaks in any of the cases
28      //do something...
29}
30
31//modification of answer by Homeless Hoopoe
Honesty
14 Oct 2018
1switch(expression) {
2   case constant-expression  :
3      statement(s);
4      break; //optional
5   case constant-expression  :
6      statement(s);
7      break; //optional
8  
9   // you can have any number of case statements.
10   default : //Optional
11      statement(s);
12}
13
Bruno
11 Jun 2020
1#include <iostream>
2using namespace std;
3int main(){
4   int num = 5;
5   switch(num + 2) {
6      case 1: 
7        cout << "Case1: Value is: " << num << endl;
8      case 2: 
9        cout << "Case2: Value is: " << num << endl;
10      case 3: 
11        cout << "Case3: Value is: " << num << endl;
12      default: 
13        cout << "Default: Value is: " << num << endl;
14   }
15   return 0;
16}
Fabiana
05 Feb 2018
1#include <iostream>
2using namespace std;
3 
4int main () {
5   // local variable declaration:
6   char grade = 'D';
7
8   switch(grade) {
9      case 'A' :
10         cout << "Excellent!" << endl; 
11         break;
12      case 'B' :
13      case 'C' :
14         cout << "Well done" << endl;
15         break;
16      case 'D' :
17         cout << "You passed" << endl;
18         break;
19      case 'F' :
20         cout << "Better try again" << endl;
21         break;
22      default :
23         cout << "Invalid grade" << endl;
24   }
25   cout << "Your grade is " << grade << endl;
26 
27   return 0;
28}
similar questions
queries leading to this page
switch statement in c 2b 2b