Switch case statement

Switch case statement:

• These statements are used to execute only specific case statements based on the switch expression.
• the syntax for switch case statement.
switch (expression)
{
case label1: statement;
break;
case label2: statement;
break;
case label3: statement;
break;
default: statement;
break;
}

 

Example

#include<stdio.h>

int main ()

{

int value_v = 3;

switch(value_v)

{

case 1: printf(“Case number statement exrcuted for value is =1 \n” );

break;

case 2: printf(“Case number statement exrcuted for value is = 2 \n” );

break;

case 3: printf(“Case number statement exrcuted for value is = 3 \n” );

break;

case 4: printf(“Case number statement exrcuted for value is = 4 \n” );

break;

default : printf(“specified Value is other than 1,2,3,4 \n” ); }

return 0;

}

Output

Case number statement exrcuted for value is = 3

WAP to create a simple calculator Performs addition, subtraction, multiplication or division depending the

# include

void main()

{

char operator1;

double firstNumber1,secondNumber1;

printf(“(+, -, *, /) Enters an operator : “);

scanf(“%c”, &operator1);

printf(“Enter two operands: “);

scanf(“%lf %lf”,&firstNumber1, &secondNumber1);

switch(operator1)

{

case ‘+': printf(“%.1lf + %.1lf = %.1lf”,firstNumber1, secondNumber1, firstNumber1+secondNumber1);

break;

case ‘-‘: printf(“%.1lf – %.1lf = %.1lf”,firstNumber1, secondNumber1, firstNumber1-secondNumber1);

break;

case ‘*': printf(“%.1lf * %.1lf = %.1lf”,firstNumber1, secondNumber1, firstNumber1*secondNumber1);

break;

case ‘/': printf(“%.1lf / %.1lf = %.1lf”,firstNumber1, secondNumber1, firstNumber1/firstNumber1);

break;

// operator is doesn’t match any case constant (+, -, *, /)

default: printf(“Error! operator is not correct”);

}

}

Output
(+, -, *,) Enters an operator : –

Enter two operands: 32.5 12.4

32.5 – 12.4 = 20.1

Leave a Reply

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