C++ program that adds, subtracts, multiplies, or divides two integers
Posted by Samath
Last Updated: November 04, 2014

Create a C++ program that adds, subtracts, multiplies, or divides two integers. The program will need to get a letter (A for addition, S for subtraction, M for multiplication, or D for division) and two integers from the user. If the user enters an invalid letter, the program should not ask the user for the two integers. Instead, it should display an appropriate error message before the program ends. If the letter is A (or a), the program should calculate and display the sum of both integers. If the letter is S (or s), the program should display the difference between both integers. When calculating the difference, always subtract the smaller number from the larger one. If the letter is M (or m), the program should display the product of both integers. If the letter is D (or d), the program should divide both integers, always dividing the larger number by the smaller one. (Utilize a switch structure).

 

Here is the Solution to the problem above:

#include <iostream>
using namespace std;

int add(int a, int b)
{
	return a + b;
}
int subtract(int a, int b)
{
	if(a>b)
	{
		return a-b;
	}
	else
	{
		return b-a;
	}
}
int multiply(int a, int b)
{
	return a * b;
}

int divide(int a, int b)
{
     if(a>b)
	{
		return a/b;
	}
	else
	{
		return b/a;
	}
}


int main(int argc, char *argv[])
{
	char op;
	int num1;
	int num2;
	cout<<"Enter (A for addition, S for subtraction, M for multiplication, or D for division): ";
	cin>>op;

	switch(op)
	{
		case 'A':
		case 'a':
			cout<<"Enter the first number: ";
	cin>>num1;
	cout<<"Enter the second number: ";
	cin>>num2;
	cout<<"Result: "<<add(num1,num2);
			break;
		case 'S':
		case 's':
			cout<<"Enter the first number: ";
	cin>>num1;
	cout<<"Enter the second number: ";
	cin>>num2;
	cout<<"Result: "<<subtract(num1,num2);
			break;
		case 'M':
		case 'm':
			cout<<"Enter the first number: ";
	cin>>num1;
	cout<<"Enter the second number: ";
	cin>>num2;
	cout<<"Result: "<<multiply(num1,num2);
			break;
		case 'D':
		case 'd':
			cout<<"Enter the first number: ";
	cin>>num1;
	cout<<"Enter the second number: ";
	cin>>num2;
	cout<<"Result: "<<divide(num1,num2);
			break;
		default: cout<<"Invalid Input";
			break;
	}
	
	return 0;
}