Block of Code

Practical Examples for Programmers

  • Home
  • C++
  • Java
  • Visual Basic
  • Discrete Math
  • Ask a Question

Calculator

Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For division, if the denominator is zero, output an appropriate message.) Some sample outputs follow:

3 + 4 = 7
13 * 5 = 65

Write the Code:

/*
Project: Calculator
Description: Simulates a calculator. User inputs two integers and chooses the
operation. The operation is performed and output.
*/

#include <iostream>;
using namespace std;

int main()
{
   // Declare Variables
   int number1, number2, menuChoice = 0;
   cout << "This program simulates a calculator.\n";
   cout << "\nPlease enter the first integer.\n";
   cin >> number1;
   cout << "\nPlease enter the second integer.\n";
   cin >> number2;
   cout << "\nPlease select from the following menu:\n";
   cout << "1. Add\n";
   cout << "2. Subtract\n";
   cout << "3. Multiply\n";
   cout << "4. Divide\n";
   cin >> menuChoice;
   switch (menuChoice)
   {
   case 1:
      cout << number1 << " + " << number2 << " = " << number1 + number2 << "\n\n";
      break;
   case 2:
      cout << number1 << " - " << number2 << " = " << number1 - number2 << "\n\n";
      break;
   case 3:
      cout << number1 << " * " << number2 << " = " << number1 * number2 << "\n\n";
      break;
   case 4:
      if (number2 != 0)
         cout << number1 << " / " << number2 << " = " << number1 / number2 << "\n\n";
      else
         cout << "Cannot divide with zero in the denominator.\n\n";
      break;
   default:
   cout << "You did not enter a valid menu choice.\n\n";
   }
   return 0;
}

Secondary Sidebar

This is the secondary sidebar

Copyright © 2025 · Metro Pro Theme on Genesis Framework · WordPress · Log in