2023-08-26|閱讀時間 ‧ 約 7 分鐘

C Programming

Section 2 : Switch

Exercise 1: Day of the Week

Take a number representing a day of the week (1 for Monday, 2 for Tuesday, ..., 7 for Sunday) as input. Output the corresponding day's name.

Input Example:

Enter a number (1-7): 3

Output Example:

The day of the week is Wednesday.


Exercise 2: Grade Evaluation

Take a numerical grade as input and output the corresponding letter grade based on the following grading criteria using the switch statement in C. A: 90-100

B: 80-89

C: 70-79

D: 60-69

F: 0-59

Input Example:

Enter your numerical grade: 87

Output example:

Your letter grade is: B






Code Example of Exercise 1

#include <stdio.h>

int main() {
int dayNumber;

// Input day number from the user
printf("Enter a number (1-7): ");
scanf("%d", &dayNumber);

// Using a switch statement to determine the day's name
switch (dayNumber) {
case 1:
printf("The day of the week is Monday.\n");
break;
case 2:
printf("The day of the week is Tuesday.\n");
break;
case 3:
printf("The day of the week is Wednesday.\n");
break;
case 4:
printf("The day of the week is Thursday.\n");
break;
case 5:
printf("The day of the week is Friday.\n");
break;
case 6:
printf("The day of the week is Saturday.\n");
break;
case 7:
printf("The day of the week is Sunday.\n");
break;
default:
printf("Invalid input. Please enter a number between 1 and 7.\n");
}

return 0;
}


Code Example of Exercise 2


#include <stdio.h>

int main() {
int numericalGrade;

// Input numerical grade from the user
printf("Enter your numerical grade: ");
scanf("%d", &numericalGrade);

// Using a switch statement to determine the letter grade
char letterGrade;
switch (numericalGrade / 10) {
case 10:
case 9:
letterGrade = 'A';
break;
case 8:
letterGrade = 'B';
break;
case 7:
letterGrade = 'C';
break;
case 6:
letterGrade = 'D';
break;
default:
letterGrade = 'F';
}

// Output the letter grade
printf("Your letter grade is: %c\n", letterGrade);

return 0;
}

It creates a switch statement that takes the value of numericalGrade / 10 as the controlling expression. This allows to group numerical grades into ranges corresponding to letter grades. This program assumes that the input grade is an integer value between 0 and 100. It rounds down to the nearest 10 to determine the letter grade based on the provided grading criteria.

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.