Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.606222'
If/else IV.
If/else IV.
Task: Determine the season:
Write a C program that prompts the user to enter a month number (1-12) and determines the corresponding season (spring, summer, autumn, or winter) using if/else statements. Display the result using printf().
Hint: if 3-5 is is sprig, if 6-8 it is summer, if 9-11 is is autumn, else it is winter, but how to check if the input is valid or not?
Solution
#include
int main() {
int monthNumber;
printf("Enter a month number (1-12): ");
scanf("%d", &monthNumber);
if (monthNumber >= 1 && monthNumber <= 12) {
if (monthNumber >= 3 && monthNumber <= 5) {
printf("The season is spring.\n");
} else if (monthNumber >= 6 && monthNumber <= 8) {
printf("The season is summer.\n");
} else if (monthNumber >= 9 && monthNumber <= 11) {
printf("The season is autumn.\n");
} else {
printf("The season is winter.\n");
}
} else {
printf("Invalid input. Please enter a month number from 1 to 12.\n");
}
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter a month number from 1 to 12. The scanf() function is used to scan the input from the user and store it in the monthNumber variable. The program uses nested if/else statements to check the value of monthNumber and determine the corresponding season using printf()