In this lesson, we will learn C++ Program to Make a Simple Mathematical calculator by using switch statements. First, we define the switch structure and see the syntax of the switch structure of the c/c++ language.
The definition and syntax of switch structure are as follows
You can copy and make a source file compiler
To understand the example you must have knowledge about the Syntax of the case statements and the basic structure of c++.
This program takes an arithmetic operator (+, -, *, /) and two operands from the user and performs the operation on those two operands depending upon the operator.
# include <iostream.h>
#include <conio.h>
void main()
{
char op;
float n1, n2;
cout << "Enter operator + or - or * or /: ";
cin >> op;
cout << "Enter two operands: ";
cin >> n1 >> n2;
switch(op)
{
case '+':
cout << n1+n2;
break;
case '-':
cout << n1-n2;
break;
case '*':
cout << n1*2;
break;
case '/':
cout << n1/n2;
break;
case '/':
cout << n1%n2;
break;
default:
cout << "wrong oprater plz inter +,-,*,/ or %";
break;
}
getch();
}
C++ and c have almost the same structure but only some differences
# include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
char op;
float n1, n2;
printf( "Enter operator + or - or * or /: ");
scanf("%c",op);
printf( "Enter two operands: ");
scanf("%f %f",&n1,&n2);
switch(op)
{
case '+':
printf("%f", n1+n2);
break;
case '-':
printf("%f", n1-n2);
break;
case '*':
printf("%f", n1*n2);
break;
case '/':
printf("%f", n1/n2);
break;
case '%':
printf("%f", n1%n2);
break;
default:
printf("wrong oprater plz inter +,-,*,/ or %");
break;
}
getch();
}