Mathematical Calculations ( MDAS )

Thursday, June 23, 2011 1 Comments A+ a-

C++ program for Mathematical calculations (MDAS)


This is a simple console application program which shows how we can do simple mathematical calculations like addition, subtraction, multiplication, division and getting the remainder using C++ programming language.


/*
Basic Mathematics program
*/
#include <iostream>

using namespace std;

int main(void)
{
 //variables
 int number1, number2, sum, difference, product, quotient, remainder;
 char pause;

 cout << "Enter first number = ";
 cin >> number1;

 cout << "Enter second number = ";
 cin >> number2;

 sum = number1 + number2;
 product = number1 * number2;

 //consider first which number is bigger
 if (number1 > number2)
 {
  difference = number1 - number2;
  quotient = number1 / number2;
  remainder = number1 % number2;
 }
 else
 {
  difference = number2 - number1;
  quotient = number2 / number1;
  remainder = number2 % number1;
 }

 cout << endl 
  << "Addition = " << sum << endl
  << "Difference = " << difference << endl
  << "Product = " << product << endl
  << "Quotient = " << quotient << endl
  << "Remainder = " << remainder << endl;

 //don't close windows console yet
 cin >> pause;

 return 0;
}


Before we proceed,  noticed that instead of always using

std::cin, std::cout and std::endl

as in our previous examples, now, each of them is already declared once through the using directive before (outside) the main function like

using std::cin;

however what we did here is specific to using only cin,cout and endl.  The purpose is to include only what are specifically used objects which are cin, cout and endl of the namespace std.
However, we could also have it this way:

using namespace std;

which uses the whole std namespace that contains cin, cout and endl. Either way you have the choice whatever implementation you like.

THE ALGORITHM : 
Now, let's take a look at the program, we can see that the user is informed to enter two numbers then the sum and product are calculated first. Then for the difference, quotient and the remainder, we first considered which of the two number has greater value so that we could get a positive result for the difference and for their quotient and remainder through the use of the if-else statement.

The operators we used:

+      //used for addition
-      //used for subtraction
*     //used for multiplication
/      //used for division
%    //modulus operation used to get the remainder of two numbers divided

1 comments:

Write comments
suman
AUTHOR
March 21, 2019 at 7:24 AM delete

nice article for beginners.thank you.
welookups C++
javacodegeeks

Reply
avatar