In this post, we will learn how to add two numbers using C++ Programming language.
This program asks the user to enter two integers, then it computes the sum of those two numbers using simple arithmetic operators.
We will see three different methods to add two numbers. They are as follows:
- Using Standard Method
- Using Function Overloading
- Using Class
So, without further ado, let’s begin this tutorial.
C++ Program to Add Two Numbers
// C++ Program to Add Two Numbers #include <iostream> using namespace std; int main(){ int num1, num2, sum; // Asking for input cout << "Enter first integer: "; cin >> num1; cout << "Enter second integer: "; cin >> num2; // Addition sum = num1 + num2; // Printing sum cout << "Sum of First and second integer is: " << sum; return 0; }
Output
Enter first integer: 5
Enter second integer: 7
Sum of First and second integer is: 12
How Does This Program Work ?
int num1, num2, sum;
In this program, we have declared three int data type variables named num1, num2 and sum.
// Asking for input cout << "Enter first integer: "; cin >> num1; cout << "Enter second integer: "; cin >> num2;
Then, the user is asked to enter the two integers.
// Addition sum = num1 + num2;
We add the two numbers using the + operator.
// Printing sum cout << "Sum of First and second integer is: " << sum;
Finally, the sum of those two numbers is printed on the screen using cout statement.
C++ Program to Add Two Numbers Using Function Overloading
// C++ Program to Add Two Numbers Using Function Overloading #include <iostream> using namespace std; int sum(int, int); float sum(float, float); float sum(int, float); int main(){ int num1, num2, x; float num3, num4, y; // Calling first function cout << "Enter two integers: "; cin >> num1 >> num2; cout << "Sum: " << sum(num1, num2) << endl; // Calling second function cout << "Enter two float numbers: "; cin >> num3 >> num4; cout << "Sum: " << sum(num3, num4) << endl; // Calling third function cout << "Enter one int and one float number: "; cin >> x >> y; cout << "Sum: " << sum(x, y) << endl; return 0; } int sum(int a, int b){ return a + b; } float sum(float a, float b){ return a + b; } float sum(int a, float b){ return a + b; }
Output
Enter two integers: 5 7
Sum: 12
Enter two float numbers: 3.4 5.1
Sum: 8.5
Enter one int and one float number: 15 7.5
Sum: 22.5
C++ Program to Add Two Numbers Using Class
// C++ Program to Add Two Numbers Using Class #include <iostream> using namespace std; class sum { int x, y; public: void input(){ cout << "Enter two integers: "; cin >> x >> y; } void add(){ cout << "Sum: " << x + y; } }; int main(){ sum m; m.input(); m.add(); return 0; }
Output
Enter two integers: 12 13
Sum: 25
Conclusion
I hope after going through this post, you understand how to add two numbers using C++ Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to solve your query.
Also Read: