Wednesday, 27 August 2014

Filled Under: ,

C++ program to add two numbers

Share
Here is simple C++ program to add two number is given below, which simply take two number and print the sum on output screen.

C++ program to add two numbers






C++ program to add two numbers


#include <iostream>
 

int main()
{
   int num1, num2, sum;
 
   cout << "Enter two numbers to add\n";
   cin >>num1>>num2;
 
   sum = num1 + num2;
   cout <<"Sum of entered numbers = " << sum << endl;
 
   return 0;
}

Output
Enter two numbers to add 6 8
Sum of entered numbers = 14

C++ program to add two numbers using class


#include <iostream>
 
class Mathematics 
{
  int num1,num2;
 
public:
  void input() {
    cout << "Input two integers\n";
    cin >>num1 >>num2;
  }
 
  void add() {
    cout << "Result = " << num1 + num2;
  }
 
};
 
int main()
{
   Mathematics m; // Creating object of class
 
   m.input();
   m.add();
 
   return 0;
}


Output
Input two integers  6 8
Result = 14


Explanation

We create Mathematics class with two functions input() and add(). First function is used to get two integers and add() performs addition and display the result. Similarly you can add more functions such as subtract, multiply, divide etc.