Switch Statement Real-Time Examples in C

SPONSOR AD

Switch Statement Real-Time Examples in C

In this article, I will discuss the Switch Statement Real-Time Examples in C. Please read our previous article discussing the basic concepts of Switch Statement in C Language. At the end of this article, you will understand how to implement the following programs using Switch Statement in C Language.

  1. State Machines Program Using Switch Statements in C Language
  2. Menu Driven Program Using Switch Statement in C Language
  3. Calculator Program using Switch Statement in C Language
  4. Game Development Program using Switch Statement in C Language
State Machines Program Using Switch Statements in C Language

Implementing a state machine using a switch statement in C is a practical and efficient approach, especially for systems where state transitions are clearly defined. A state machine consists of a set of states, transitions between these states, and actions that occur in each state or on transitions. Here’s a simplified example to illustrate this concept:

Example: Traffic Light Controller

Consider a traffic light system with three states: Red, Green, and Yellow. The traffic light changes state in the order: Red → Green → Yellow → Red, and so on.

Defining the States

First, define an enumeration for the states:

SPONSOR AD
typedef enum {
    RED,
    GREEN,
    YELLOW
} TrafficLightState;
State Machine Function

Create a function to handle the state transitions and actions:

void updateTrafficLight(TrafficLightState *state) {
    switch (*state) {
        case RED:
            // Action for Red state (e.g., turn on red light)
            printf("Red light\n");
            *state = GREEN;  // Transition to Green
            break;
        case GREEN:
            // Action for Green state (e.g., turn on green light)
            printf("Green light\n");
            *state = YELLOW;  // Transition to Yellow
            break;
        case YELLOW:
            // Action for Yellow state (e.g., turn on yellow light)
            printf("Yellow light\n");
            *state = RED;  // Transition back to Red
            break;
        default:
            // Handle unexpected state
            printf("Unknown state\n");
            *state = RED;  // Reset to initial state
    }
}
Main Program Loop

Simulate the traffic light operation in the main function:

#include <stdio.h>
#include <unistd.h>  // For sleep()

int main() {
    TrafficLightState currentState = RED;  // Initial state

    while (1) {  // Infinite loop to simulate continuous operation
        updateTrafficLight(&currentState);
        sleep(1);  // Wait for a second before changing state (adjust time as needed)
    }

    return 0;
}

In this program, the updateTrafficLight function takes the current state as input, performs the action associated with that state (like lighting up the corresponding light), and decides the next state. The state transition logic is encapsulated within the switch statement.

This is a basic example, and real-world state machines can be more complex, involving multiple variables, conditions for state transitions, and different kinds of actions (like entry, exit, and during actions for states). State machines are widely used in embedded systems, UI development, protocol design, and more.

Menu Driven Program Using Switch Statement in C Language

A menu-driven program in C using a switch statement typically involves presenting a list of options to the user and executing different code sections based on the user’s selection. Below is a simple example of such a program. This example is a basic calculator that allows the user to choose an operation (addition, subtraction, multiplication, division) and then input two numbers to perform the chosen operation.

#include <stdio.h>

int main() {
    int choice;
    float num1, num2, result;

    while(1) {
        printf("\nSimple Calculator\n");
        printf("1. Addition\n");
        printf("2. Subtraction\n");
        printf("3. Multiplication\n");
        printf("4. Division\n");
        printf("5. Exit\n");
        printf("Enter your choice (1-5): ");
        scanf("%d", &choice);

        if (choice == 5) break; // Exit condition

        printf("Enter first number: ");
        scanf("%f", &num1);
        printf("Enter second number: ");
        scanf("%f", &num2);

        switch(choice) {
            case 1:
                result = num1 + num2;
                printf("Result: %.2f\n", result);
                break;
            case 2:
                result = num1 - num2;
                printf("Result: %.2f\n", result);
                break;
            case 3:
                result = num1 * num2;
                printf("Result: %.2f\n", result);
                break;
            case 4:
                if (num2 != 0) {
                    result = num1 / num2;
                    printf("Result: %.2f\n", result);
                } else {
                    printf("Error: Division by zero\n");
                }
                break;
            default:
                printf("Invalid choice. Please choose between 1-5.\n");
        }
    }

    printf("Program exited.\n");
    return 0;
}

In this program:

  • A while loop continuously displays the menu until the user chooses to exit (option 5).
  • The switch statement evaluates the user’s choice and executes the corresponding case block.
  • Each case block performs the operation (addition, subtraction, multiplication, or division) based on the user’s input and then breaks out of the switch.
  • The default case provides an error message if the user enters a number other than 1-5.
Calculator Program using Switch Statement in C Language

Creating a simple calculator program using a switch statement in C is a great way to understand how to use switch cases for decision-making. The program will allow the user to perform basic arithmetic operations like addition, subtraction, multiplication, and division in this example. Here’s how you can do it:

SPONSOR AD
#include <stdio.h>

int main() {
    char operator;
    double firstNumber, secondNumber;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);

    printf("Enter two operands: ");
    scanf("%lf %lf", &firstNumber, &secondNumber);

    switch (operator) {
        case '+':
            printf("%.1lf + %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber + secondNumber);
            break;
        case '-':
            printf("%.1lf - %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber - secondNumber);
            break;
        case '*':
            printf("%.1lf * %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber * secondNumber);
            break;
        case '/':
            if(secondNumber != 0.0)
                printf("%.1lf / %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber / secondNumber);
            else
                printf("Division by zero!\n");
            break;
        default:
            printf("Error! Operator is not correct\n");
    }

    return 0;
}

In this program:

  • The user is prompted to enter an operator (+, -, *, /) and two operands (numbers).
  • The switch statement executes the corresponding arithmetic operation based on the operator entered.
  • Each case in the switch handles a different arithmetic operation.
  • In the case of division (/), the program checks if the second operand is zero to avoid division by zero.
  • If the operator does not match any cases (+, -, *, /), the default case is executed, indicating an error in the operator input.
  • Compile and run this program, and you’ll have a basic console-based calculator to perform the four fundamental arithmetic operations!
Game Development Program using Switch Statement in C Language

Creating a simple game using the switch statement in C is a great way to learn about control structures and game logic. Let’s design a basic number-guessing game. In this game, the computer randomly selects a number, and the player has to guess it. The switch statement will be used to respond to the player’s guesses. Here’s a basic outline of the program:

  • Initialize the game: Set up variables and generate a random number.
  • Game Loop: Keep the game running until the player guesses correctly or decides to quit.
  • User Input: Ask the player to guess a number or quit the game.
  • Process the Guess: Use a switch statement to provide feedback or end the game.

Sample Code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int secretNumber, guess, numberOfTries = 0;
    char choice;

    // Initialize random seed
    srand(time(NULL));

    // Generate a random number between 1 and 100
    secretNumber = rand() % 100 + 1;

    printf("Welcome to the Number Guessing Game!\n");
    printf("Guess a number between 1 and 100, or press 'q' to quit.\n");

    do {
        printf("Enter your guess: ");
        scanf(" %c", &choice);

        // Check if the player wants to quit
        if (choice == 'q' || choice == 'Q') {
            printf("You chose to quit. Goodbye!\n");
            break;
        }

        // Convert char to int for comparison
        guess = choice - '0'; 
        numberOfTries++;

        switch (guess) {
            case 0 ... 100: // Check if the guess is within the range
                if (guess == secretNumber) {
                    printf("Congratulations! You guessed the right number in %d tries!\n", numberOfTries);
                    return 0;
                } else if (guess < secretNumber) {
                    printf("Too low! Try again.\n");
                } else {
                    printf("Too high! Try again.\n");
                }
                break;
            default:
                printf("Invalid input. Please guess a number between 1 and 100.\n");
        }
    } while (guess != secretNumber);

    return 0;
}
How the Game Works:
  • Random Number Generation: The game starts by generating a random number between 1 and 100.
  • Guessing and Feedback: The player enters a guess, and the program uses a switch statement to determine if the guess is too low, too high, or correct.
  • Winning the Game: If the player guesses the correct number, the game congratulates them and ends.
  • Quitting the Game: The player can quit the game at any time by entering ‘q’.

This program is a basic example and can be extended with more features, such as limiting the number of tries, adding difficulty levels, or improving user input handling. It demonstrates the use of switch statements for decision-making in a simple game context.

Switch Statement Real-Time Examples in C

Here are several real-world scenarios in real-time programming where switch statements are effectively used:

  • Menu-Driven Interfaces: In applications like ATMs, vending machines, or medical devices with user interfaces, switch statements can manage user inputs. Each case in the switch corresponds to a different menu option, leading to different functionalities.
  • State Machine Implementation: For systems that operate in distinct states, such as a traffic light control system or a manufacturing line, switch statements can manage state transitions. Each case represents a different state, and the system transitions between states based on inputs or events.
  • Protocol Message Handling: In communication systems, switch statements can handle different types of messages or commands received. Each case processes a specific type of message, allowing for organized and efficient handling of communication protocols.
  • Device Control: In embedded systems controlling hardware, switch statements can be used to respond to different command codes. For instance, in a robotic control system, different commands might control movement, activation of tools, or sensor readings.
  • Keyboard Input Processing: For applications that involve keyboard input or button presses, switch statements can categorize different key codes and execute specific actions for each key.
  • Error Handling: In systems where various error codes can be returned from functions or procedures, switch statements can handle each specific error code differently, providing detailed error management.
  • Task Scheduling: In real-time operating systems, switch statements can be used in the task scheduler to dispatch tasks based on their priority or type.
  • Signal Processing: In applications like digital signal processing, switch cases can be used to apply different algorithms or processing techniques based on the type of signal or user selection.

In the next article, I will discuss While Loop in C Language with Examples. In this article, I try to explain Switch Statements in Real-Time Examples in C Language. I hope you enjoy this article on Switch Statements in Real-time Examples in C Language. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *