Make a calculator using if-else-if else statement which perform the addition, subtraction, multiplication, division and remainder operations. Take values and operator from user on runtime. Use do while loop for user choice. Means after performing one operation program will ask from user “do you want to do another calculation(yes/no)? ”. If user press then user will enter number 1, number 2 and operator for calculation and if user press no then terminate the loop.
Update your calculator using functions (Calculator you implemented in do while loop .Create separate functions for addition, subtraction, division, multiplication and remainder operations).
#include <iostream>
#include <string>
using namespace std;
int Sum(int a, int b) { return a + b; }
int Multiple(int a, int b) { return a * b; }
int Subtract(int a, int b) { return a - b; }
int Divide(int a, int b)
{
if (b == 0) return 0;
else return a / b;
}
int Remain(int a, int b)
{
if (b == 0) return 0;
else return a % b;
}
int main()
{
int a, b;
char ch;
do
{
system("cls");
cout << "First number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
cout << "Enter operation(+, - , *, /, %): ";
cin >> ch;
if (ch == '+') cout << a << " " << ch << " " << b << " = " << Sum(a, b) << endl;
else if (ch == '-') cout << a << " " << ch << " " << b << " = " << Subtract(a, b) << endl;
else if (ch == '*') cout << a << " " << ch << " " << b << " = " << Multiple(a, b) << endl;
else if (ch == '/') cout << a << " " << ch << " " << b << " = " << Divide(a, b) << endl;
else if (ch == '%') cout << a << " " << ch << " " << b << " = " << Remain(a, b) << endl;
else cout << "You enter wrong operator." << endl;
cout << endl;
cout << "Do you want to do another calculation(yes/no)? ";
string temp;
cin >> temp;
if (temp == "no") break;
system("pause");
} while (true);
return 0;
}
Comments
Leave a comment