Consider a situation in which, only one block of code needs to be executed among many blocks. This type of situation can be handled using nested if...else statement but, the better way of handling this type of problem is using switch...case statement.
Consider a situation in which, only one block of code needs to be executed among many blocks. This type of situation can be handled using nested if...else statement but, the better way of handling this type of problem is using switch...case statement.
ORIGINAL SOURCE CODE = PROGRAMIZ
#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout<<"Select an operator either + or - or * or / \n";
cin>>o;
cout<<"Enter two operands: ";
cin>>num1>>num2;
switch(o) {
case '+':
cout<<num1<<" + "<<num2<<" = "<<num1+num2;
break;
case '-':
cout<<num1<<" - "<<num2<<" = "<<num1-num2;
break;
case '*':
cout<<num1<<" * "<<num2<<" = "<<num1*num2;
break;
case '/':
cout<<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;
}
COMMENTS