Switch Statement in C

Learn how to use switch statements in C programming with simple examples. A beginner-friendly guide running on Debian 12 with Vim.
Switch Statement in C Programming
The switch statement in C lets you execute one block of code out of many options based on the value of a variable. It's an alternative to multiple if-else statements for cleaner code.
What is a Switch Statement?
A switch evaluates an expression and jumps to the matching case label. If no case matches, the default block executes.
Example Code
This program prints the name of the day based on a number input (1-7):
#include
int main()
int day;
printf(\\"Enter a number (1-7): \\");
scanf(\\"%d\\", &day);
switch(day)
case 1:
printf(\\"Sunday\\\
\\");
break;
case 2:
printf(\\"Monday\\\
\\");
break;
case 3:
printf(\\"Tuesday\\\
\\");
break;
case 4:
printf(\\"Wednesday\\\
\\");
break;
case 5:
printf(\\"Thursday\\\
\\");
break;
case 6:
printf(\\"Friday\\\
\\");
break;
case 7:
printf(\\"Saturday\\\
\\");
break;
default:
printf(\\"Invalid input! Please enter a number between 1 and 7.\\\
\\");
return 0;
Compiling and Running
To compile and run on Debian 12:
gcc switch.c -o switch
./switch
Expected Output
Enter a number (1-7): 3
Tuesday
Conclusion
Switch statements make your code more organized when checking multiple constant values. Practice by adding more cases.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/switch-statement-in-c/?feed_id=12652&_unique_id=688af4082e6e6
Comments
Post a Comment