0
0
Cprogramming~5 mins

Use cases

Choose your learning style9 modes available
Introduction
Use cases help us understand when and why to write certain parts of a program. They show real situations where code is useful.
When you want to check if a number is positive or negative.
When you need to decide what message to show based on user input.
When you want to perform different actions depending on a value.
When you want to organize your program to handle different tasks clearly.
Syntax
C
switch (variable) {
    case value1:
        // code to run if variable == value1
        break;
    case value2:
        // code to run if variable == value2
        break;
    default:
        // code to run if variable does not match any case
        break;
}
The switch statement checks a variable against different values.
Use break; to stop checking after a match is found.
Examples
This example prints the name of the day based on the number.
C
int day = 3;
switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    default:
        printf("Another day\n");
        break;
}
This example prints a message based on the grade letter.
C
char grade = 'B';
switch (grade) {
    case 'A':
        printf("Excellent\n");
        break;
    case 'B':
        printf("Good\n");
        break;
    case 'C':
        printf("Average\n");
        break;
    default:
        printf("Needs Improvement\n");
        break;
}
Sample Program
This program asks the user to enter a number and prints a message based on the choice using a switch statement.
C
#include <stdio.h>

int main() {
    int number;
    printf("Enter a number between 1 and 3: ");
    scanf("%d", &number);

    switch (number) {
        case 1:
            printf("You chose option 1\n");
            break;
        case 2:
            printf("You chose option 2\n");
            break;
        case 3:
            printf("You chose option 3\n");
            break;
        default:
            printf("Invalid option\n");
            break;
    }

    return 0;
}
OutputSuccess
Important Notes
Always include a default case to handle unexpected values.
Remember to use break; after each case to avoid running multiple cases.
Switch works best with simple values like integers or characters.
Summary
Use cases help decide what code to run based on values.
The switch statement is a clean way to handle multiple choices.
Always handle unexpected values with a default case.