on
Italy
- Get link
- X
- Other Apps
switch statement.switch (n) {
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
case, the relevant codes are executed and control moves out of the switch statement. If the n doesn't matches any of the constant in case, then the default codes are executed and control moves out of switch statement.
/* C program to demonstrate the working of switch...case statement */
/* C Program to create a simple calculator for addition, subtraction,
multiplication and division */
# include
int main() {
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}
Enter operator either + or - or * or / * Enter two operands: 2.3 4.5 2.3 * 4.5 = 10.3
break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed.
Comments
Post a Comment