In this tutorial, we will write a C++ program for the addition of two numbers. We can add the integers, floats, double, etc using the same program just changing the type.
The program takes the user inputs for the number to be added then displays the result. We will see to add two numbers in three different ways in C++
- Add two numbers in main function
- Add two numbers using function
- Add Two Numbers in using Class
C++ Program to Add Two Numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int num1, num2, sum; cout << "Enter First Numbers: "; cin >> num1; cout << "Enter Second Numbers: "; cin >> num2; sum = num1 + num2; cout << "\nAddition Result: " << sum; return 0; } |
Output:
Enter First Numbers: 5
Enter Second Numbers: 3
Addition Result: 8
You can change the data type as required and use the same code.
Add two numbers using Function in C++
The program takes the user input the same as above, the only difference is the function is created for the calculation and return the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<iostream> using namespace std; int add(int n1, int n2) { return (n1 + n2); } int main() { int num1, num2, sum; cout << "Enter First Numbers: "; cin >> num1; cout << "Enter Second Numbers: "; cin >> num2; sum = add(num1, num2); cout << "\nAddition Result: " << sum; return 0; } |
Output:
Enter First Numbers: 20
Enter Second Numbers: 5
Addition Result: 25
Add Two Numbers in C++ using Class
Here separate class is created to get the values and add the numbers and return to the main function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <iostream> using namespace std; class AddClass { private: int num1, num2; public: void getData() { cout << "Enter First Numbers: "; cin >> num1; cout << "Enter Second Numbers: "; cin >> num2; } int add() { return (num1 + num2); } }; int main() { int sum; AddClass obj; obj.getData(); sum = obj.add(); cout << "\nAddition result: " << sum; return 0; } |
Output:
Enter First Numbers: 10
Enter Second Numbers: 6
Addition result: 16