Addition of two numbers in C++

By | May 27, 2020

In this article, we have discussed various methods to add two numbers in C++. These are simple program, you can learn them easily.

Method-1 : With Hardcoded Inputs

#include <iostream>
using namespace std;

/driver
int main() {

   // first number is 5
   int x = 5;

   // second number is 6
   int y = 6;

   // resultant number
   int sum = x + y;
   cout << sum;
   return 0;
} 

Output:

11 

Method-2 : With user Inputs

#include <iostream>
using namespace std;

// driver
int main() {

   // for inputs
   int x, y;

   // for output
   int sum;

   cout << "first number: ";
   cin >> x;
   cout << "second number: ";
   cin >> y;
   
   // sum of both numbers
   sum = x + y;
   cout << "Sum is: " << sum;
   return 0;
}

Output:
Output depends on user inputs, that will be sum of both numbers.

Method-3 : With class

#include <iostream>
using namespace std;

class sum {
 
  // for inputs
  int x, y;

public:
  // input numbers
  void input() {
    cout << "Input two integers\n";
    cin >> x >> y;
  }
  void add() {
    // sum of both numbers
    cout << "Result: " << x + y;
  }
};

// driver
int main()
{ 
   // object of class
   sum m; 

   m.input();
   m.add();

   return 0;
}

Output:
Output depends on user inputs, that will be sum of both numbers.

Method-4 : With array elements

#include <iostream>
using namespace std;

//driver
int main() {

   // create array
   int a[3];

   // initialize array 
   a[0]=5;
   a[1]=10;

   // sum of first two elements
   a[2]=a[0] + a[1];
   cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
   return 0;
}

Output:

Sum of 5 and 10 is 15 



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.