# Skenz - How To Wiki

### Site Tools

cs:c_language:switch

# Switch statement

Concepts:
`switch` and `if` statements, different ways to write and indent a program

Text:
Write a program using the `if` or the `switch` statement that, given in input a number, recognize the following commands:

Command Input Number
Down 2
Up 8
Left 4
Right 6

Solution:
A number of 5 equivalent solutions are reported in the following. Probably, the last one based on the `switch` statement, is the more readable.

Solution 1:
This solution is based on the `if` statement and on a flag variable `cmd_executed` used to specify if a command (i.e., `2`, `4`, `6`, `8`) has been correctly recognized.

switch_a.c
```#include <stdio.h>

int main(){
int cmd;
int cmd_executed=0;

printf("Insert a command: ");
scanf("%d", &cmd);

if(cmd==2){
printf("Down\n");
cmd_executed=1;
}
if(cmd==8){
printf("Up\n");
cmd_executed=1;
}
if(cmd==4){
printf("Left\n");
cmd_executed=1;
}
if(cmd==6){
printf("Right\n");
cmd_executed=1;
}
if(!cmd_executed){
printf("ERROR: incorrect command!\n");
}

return 0;
}```

Solution 2:
This solution is based only on the `if` statement, without the used of the flag variable

switch_b.c
```#include <stdio.h>

int main(){
int cmd;

printf("Insert a command: ");
scanf("%d", &cmd);

if(cmd==2){
printf("Up\n");
}else{
if(cmd==8){
printf("Down\n");
}else{
if(cmd==4){
printf("Left\n");
}else{
if(cmd==6){
printf("Right\n");
}else{
printf("ERROR: incorrect command!\n");
}
}
}
}

return 0;
}```

Solution 3:
Same as Solution 2, but without braces in the `if` statement.

switch_c.c
```#include <stdio.h>

int main(){
int cmd;

printf("Insert a command: ");
scanf("%d", &cmd);

if(cmd==2)
printf("Down\n");
else
if(cmd==8)
printf("Up\n");
else
if(cmd==4)
printf("Left\n");
else
if(cmd==6)
printf("Right\n");
else
printf("ERROR: incorrect command!\n");

return 0;
}```

Solution 4:
This solution is exactly equivalent to the one reported in Solution 3, only indentation changes

switch_d.c
```#include <stdio.h>

int main(){
int cmd;

printf("Insert command: ");
scanf("%d", &cmd);

if(cmd==2)
printf("Down\n");
else if(cmd==8)
printf("Up\n");
else if(cmd==4)
printf("Left\n");
else if(cmd==6)
printf("Right\n");
else
printf("ERROR: incorrect command!\n");

return 0;
}```

Solution 5:
Finally, this solution is based on the use of the `switch` statement

switch_e.c
```#include <stdio.h>

int main(){
int cmd;

printf("Insert command: ");
scanf("%d", &cmd);

switch(cmd){
case 2:
printf("Down\n");
break;

case 8:
printf("Up\n");
break;

case 4:
printf("Left\n");
break;

case 6:
printf("Right\n");
break;

default:
printf("ERROR: incorrect command!\n");
}

return 0;
}```