switch Statement in C

  • February 22, 2022
  • C
Matrix multiplication

The switch statement in C provide us with an alternate way to implement the if-else if ladder in a much more simplified manner because the syntax of the switch statement is much easier to read and write.

The syntax for switch statement:
switch(expression){    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......    
    
default:     
code to be executed if  none of the cases match;    
}    

here, case value1, case value2…. are the various cases that a user might select. The default case is to be executed if none of the cases are matched. The break is a keyword in C that is used to bring the program control out of the loop.

Flowchart:
Some rules to be followed to create a switch block:
  • The switch expression must be an integer or character type.
  • The case value must be an integer or character constant.
  • The case value can be used only inside the switch statement.
  • The break statement in the switch case is not a must. It is optional. If there is no break statement found in the case, all the cases will be executed that are present after the matched case. It is known as fall through the state of C switch statement.
  • If there is no default case, then the program simply falls through the entire switch and continues with the next instruction(if any), that follows the closing brace of the switch.
Example: Simple Calculator
// Program to create a simple calculator
#include <stdio.h>

int main() {
    char operation;
    double n1, n2;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operation);
    printf("Enter two operands: ");
    scanf("%lf %lf",&n1, &n2);

    switch(operation)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
            break;

        // operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! operator is not correct");
    }

    return 0;
}
Output:
Enter an operator (+, -, *, /): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

Note: also read about  Decision-Making in C & if-else Statement.

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

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