Switch Case
Part of the Fundamentals section of Coddy's C journey — lesson 28 of 63.
The switch statement is a multi-way decision maker that tests whether an expression matches one of several constant integer values, and branches accordingly.
First, define an integer to use with switch:
int day = 3;Then create a switch statement that evaluates the variable:
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
}In this example:
- Each
caserepresents a possible value ofday - When
dayequals3, "Wednesday" will be printed
- The
breakstatement exits the switch - The
defaultcase handles all values not explicitly covered
Without break, execution would "fall through" to the next case.
Challenge
EasyWrite a program that uses a switch statement to convert a numeric grade to a letter grade as follows:
- 90-100: 'A'
- 80-89: 'B'
- 70-79: 'C'
- 60-69: 'D'
- Below 60: 'F'
Your program should read a numeric grade (0-100) and print the corresponding letter grade. Use integer division by 10 to categorize the grades.
If you struggle, follow the example from the lesson
Try it yourself
#include <stdio.h>
int main() {
int grade;
scanf("%d", &grade);
// Don't change above this line
// Write your code here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Control Flow
If StatementIf - ElseElse-IfSwitch CaseTernary Conditional OperatorRecap ChallengeNested If - Else3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge