C case statement
Created By: chatGPT
In C programming, a case statement is part of the switch statement, which allows you to execute different parts of code based on the value of a variable. It provides a convenient way to handle multiple conditions compared to using multiple if-else statements. Below is a simple example demonstrating how to use a switch-case structure.
#include <stdio.h>
int main() {
int day;
printf("Enter a number (1-7) for the day of the week: ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid input! Please enter a number between 1 and 7.\n");
break;
}
return 0;
}
In this code: The user is prompted to enter a number corresponding to a day of the week. The switch statement then checks the value of the day variable. Each case corresponds to a specific day, and when a matching case is found, the code associated with that case executes. The break statement ensures that the program exits the switch once a case is processed, preventing fall-through to the subsequent cases. If the input does not match any case, the default case provides a message indicating invalid input.
// Example of the full program execution:
// Input: 3
// Output: Wednesday