You are here

C++ program to add two numbers

C++ program to add two numbers.

C++ programming code

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.    int a, b, c;
  8.    
  9.    cout << "Enter two integers to add\n";
  10.    cin >> a >> b;
  11.  
  12.    c = a + b;
  13.    cout <<"Sum of the numbers: " << c << endl;
  14.    
  15.    return 0;
  16. }

C++ addition program using class

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Mathematics {
  6.   int x, y;
  7.  
  8. public:
  9.   void input() {
  10.     cout << "Input two integers\n";
  11.     cin >> x >> y;
  12.   }
  13.  
  14.   void add() {
  15.     cout << "Result: " << x + y;
  16.   }
  17.  
  18. };
  19.  
  20. int main()
  21. {
  22.    Mathematics m; // Creating an object of the class
  23.  
  24.    m.input();
  25.    m.add();
  26.  
  27.    return 0;
  28. }

We create Mathematics class with two functions input and add. Function input is used to get two integers from a user, and function add performs the addition and displays the result. Similarly, you can create more functions to subtract, multiply, divide.