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

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.