Answer to Question #300227 in C++ for king

Question #300227

Discuss switch case statement in C language programming language by taking a suitable example


1
Expert's answer
2022-02-22T08:58:00-0500
The switch statement allows us to execute one code block among many alternatives.

You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.

Syntax of switch...case
switch (expression)
​{
    case constant1:
      // statements
      break;

    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}



Example:



#include <stdio.h>


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


    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operation);
    printf("Enter operand 1: ");
    scanf("%lf",&n1);
	printf("Enter operand 2: ");
    scanf("%lf",&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;
        default:
            printf("Error! operator is not correct");
    }
	scanf("%lf",&n2);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog