In this lesson we will learn a C++ program to make a simple mathematical calculator by using a switch statement. 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 statement 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 program for simple calculator
C++ and c have almost same structure but only some differences
- In the C++ preprocessing directive iostream. h is used for including standard input/output functions, while in the C language stdio. h is used
- For output cout is used in C++, while in the C language, printf is used for output
- In C++, cin is used for getting input from the user, while in C coding, the scanf function is used for getting input from the user.
- In C++, format specifiers are not used to print output and for getting input, while format specifiers are used in C coding.
# 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();
}