C (programming language)
C program to print day of week using switch-case
Understanding the Problem
- The goal is to create a C program that determines the day of the week based on a given numerical input (1-7) and prints the corresponding day name using a switch-case structure.
- This structure offers a clear and efficient way to handle multiple conditional branches based on a single variable’s value.
Code Structure and Explanation
C
#include <stdio.h>
int main() {
int dayNumber;
printf("Enter a day number (1-7): ");
scanf("%d", &dayNumber);
switch (dayNumber) {
case 1:
printf("Day of the week: Monday\n");
break;
case 2:
printf("Day of the week: Tuesday\n");
break;
case 3:
printf("Day of the week: Wednesday\n");
break;
case 4:
printf("Day of the week: Thursday\n");
break;
case 5:
printf("Day of the week: Friday\n");
break;
case 6:
printf("Day of the week: Saturday\n");
break;
case 7:
printf("Day of the week: Sunday\n");
break;
default:
printf("Invalid day number\n");
break;
}
return 0;
}
Explanation:
- Header Inclusion:
#include <stdio.h>
provides input/output functions likeprintf
andscanf
. - Main Function: The program’s execution begins in the
main
function. - Variable Declaration:
int dayNumber;
declares an integer variable to store the user’s input. - User Input:
printf
prompts the user to enter a day number, andscanf
reads the input and stores it indayNumber
. - Switch Statement:
- The
switch (dayNumber)
statement evaluates the value ofdayNumber
. - Each
case
label represents a valid day number (1-7). - If
dayNumber
matches acase
label, the corresponding code block executes, printing the associated day name. - The
break
statement exits the switch statement after executing a case block. - The
default
case handles any value ofdayNumber
that doesn’t match the specified cases, indicating an invalid input.
- The
- Return Statement:
return 0;
indicates successful program termination.
Key Points:
- The switch-case structure provides a clean and efficient way to handle multiple conditional branches based on a single variable’s value.
- It’s often preferred over multiple
if-else if
statements when dealing with several possible values for a variable. - Ensure each case block has a
break
statement to prevent unintended execution of subsequent cases. - The
default
case is optional but serves as a catch-all for unexpected values. - Consider using a loop to allow for repeated day number entry and day name printing if needed.
- For more advanced date and time handling, explore C’s standard library functions like
time.h
.