Add and Multiply 2 Numbers

Monday, June 20, 2011 0 Comments A+ a-

C++ program to Add and Multiply two numbers


Let me show you a simple C++ console application program which will add two numbers and show their sum and product.


/*
Addition and Multiplication of two numbers
*/
#include <iostream>

using namespace std;

int main(void)
{
 //variables
 int number1, number2, sum, product;
 char stay;

 cout << "Input first number: ";
 cin >> number1;

 cout << endl << "Input second number: ";
 cin >> number2;
 
 // add the two numbers
 sum = number1 + number2;
 
 cout << endl << "The sum is " << sum <<endl;

 // multiply the two numbers directly within cout
 cout << endl << "The product is " << number1 * number2 << endl;
 
 //let console wait for an input before exit 
 cin >> stay;

 return 0;
}


Now let us go through the implementation. As we have seen we defined 4 variables:
  1. number1 and number2 - to hold the values of the two numbers
  2. sum - to hold the value of  the sum of number1 and number2
  3. stay - to let the program ask for an input before the console window closes. 
Now maybe you would notice that I did not defined a variable which will hold the value of the product of these two numbers. The answer is because I would like you to know or notice that aside from saving the product into another variable like what we did with the sum.

We can also directly process the calculation within cout and have it processed directly for output. But this would depend on the implementation the program would require and for this one this can just be applied as what we wanted was directly print the results of multiplying two numbers.

Output: