Switch
Switch
The switch statement tests the value of a variable and compares it with multiple
cases. Once the case match is found, a block of statements associated with that
particular case is executed.
Each case in a block of a switch has a different name / number which is referred to
as an identifier. The value provided by the user is compared with all the cases inside the
switch block until the match is found.
If a case match is found, then the default statement is executed, and the control
goes out of the switch block.
switch
break +
case 1 BLOCK 1
-
break +
case 2 BLOCK 2
break +
default default
statement-x
int n;
int main(void)
{
scanf("%d", &n);
switch (n % 2 == 0)
{
case 1:
puts("EVEN");
break;
case 0:
puts("ODD");
}
return 0;
}
#include <stdio.h>
int n;
int main(void)
{
scanf("%d", &n);
switch (n)
{
case 1:
case 2:
case 3:
printf("Initial\n");
break;
case 4:
case 5:
case 6:
printf("Average\n");
break;
case 7:
case 8:
case 9:
printf("Sufficient\n");
break;
default:
printf("High\n");
}
return 0;
}
E-OLYMP 923. Season Determine the season name by the month number.
► Let n (1 ≤ n ≤ 12) be the month number. Use switch statement to solve the
problem.
#include <stdio.h>
int n;
int main(void)
{
scanf("%d", &n);
switch (n)
{
case 1:
case 2:
case 12:
puts("Winter");
break;
case 3:
case 4:
case 5:
puts("Spring");
break;
case 6:
case 7:
case 8:
puts("Summer");
break;
default:
puts("Autumn");
}
return 0;
}
int n;
int main(void)
{
scanf("%d", &n);
switch (n > 0)
{
case 1:
puts("Positive");
break;
case 0:
switch (n < 0)
{
case 1:
puts("Negative");
break;
default:
puts("Zero");
}
}
return 0;
}
int a, b, res;
char c;
int main(void)
{
scanf("%d %c %d", &a, &c, &b);
switch (c)
{
case '+':
res = a + b;
break;
case '-':
res = a - b;
break;
case '*':
res = a * b;
break;
case '/':
res = a / b;
}
printf("%d\n", res);
return 0;
}