C Program to print DAY according to user input for day count
Objective
Write a C program to print the Day of the Week based on a number (1-7) using the switch-case statement.
Algorithm / Approach
- Read an integer from the user representing the day number.
- Pass the integer into a
switch(i)statement. - Create
case 1:throughcase 7:, each printing the corresponding day string (Monday - Sunday). - Append a
break;statement at the end of every case block. - Provide a
default:block to handle invalid numbers (like 8 or 9).
main.c
#include<stdio.h>
int main( ) {
int i;
printf("Enter Day Number : ");
scanf("%d",&i);
switch(i) {
case 1:
printf("DAY IS MONDAY\n");
break;
case 2:
printf("DAY IS TUESDAY\n");
break;
case 3:
printf("DAY IS WEDNESDAY\n");
break;
case 4:
printf("DAY IS THURSDAY\n");
break;
case 5:
printf("DAY IS FRIDAY\n");
break;
case 6:
printf("DAY IS SATURDAY\n");
break;
case 7:
printf("DAY IS SUNDAY\n");
break;
default:
printf("WRONG CHOICE \n");
}
return 0;
}
Expected Output
Enter Day Number : 3 DAY IS WENESDAY Enter Day Number : 9 WRONG CHOICE
Explanation of the Program
- A
switchstatement is an elegant alternative to a massive if-else-if ladder when you are comparing a single variable against exact, distinct integer or character values. - The
breakkeyword is absolutely critical. Once a matching case is found, C executes that block AND continues executing all blocks below it (a phenomenon called "fall-through") unless it hits abreak;command to exit the switch.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)