Introduction:
The switch statement is a multi-way decision-making statement in C. It allows a program to choose one block of code from multiple options based on the value of an expression.
In this program, the user enters a number between 1 and 7. The program uses the switch statement to display the corresponding weekday.
Definition:
A switch statement compares the value of a variable with different case labels. When a matching case is found, the corresponding block of code is executed. If no case matches, the default block is executed.
Syntax:
switch(expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
...
default:
statements;
}
Explanation:
switch statement checks the entered value.case, the corresponding weekday is displayed.break statement stops execution after the matching case.default case displays "Not A Valid Weekday".
Explanation: This program accepts a number from 1 to 7 and displays the corresponding weekday using the switch statement.
#include <stdio.h> #include <conio.h> main() { int k; clrscr(); printf("Enter a Number : "); scanf("%d",&k); switch(k) { case 1: printf("\nMonday"); break; case 2: printf("\nTuesday"); break; case 3: printf("\nWednesday"); break; case 4: printf("\nThursday"); break; case 5: printf("\nFriday"); break; case 6: printf("\nSaturday"); break; case 7: printf("\nSunday"); break; default: printf("\nNot A Valid Weekday"); } getch(); }
Output:
switch statement to display the name of a month based on the month number entered by the user (1–12).switch statement to select and execute one of multiple cases based on user input.switch(month) with case 1 to case 12 and a default case for invalid input.#include <stdio.h> #include <conio.h> main() { int month; clrscr(); printf("Enter Month Number (1-12) : "); scanf("%d",&month); switch(month) { case 1: printf("\nJanuary"); break; case 2: printf("\nFebruary"); break; case 3: printf("\nMarch"); break; case 4: printf("\nApril"); break; case 5: printf("\nMay"); break; case 6: printf("\nJune"); break; case 7: printf("\nJuly"); break; case 8: printf("\nAugust"); break; case 9: printf("\nSeptember"); break; case 10: printf("\nOctober"); break; case 11: printf("\nNovember"); break; case 12: printf("\nDecember"); break; default: printf("\nInvalid Month Number"); } getch(); }
switch statement to display the corresponding month name. If the entered number is outside the range 1 to 12, it displays "Invalid Month Number".