C++ Program to Enter Two Numbers and Find their Sum
ADVERTISEMENTS
C++ program to enter two numbers and find their sum.
In this article, you will learn how to find the sum of two numbers entered by the user.
Example
Enter two integer values::
5
7
Result:: 5 + 7 = 12
5
7
Result:: 5 + 7 = 12
We will solve this problem in three approaches:
- Using the Integer values
- Using the minimal variables
- Using the Real values
You should know about the following topics in C++ programming to understand this program:
- C++ Variables
Example-1 Using the Integer values
// C++ program to find the sum of two integers
#include <iostream>
using namespace std;
// It's the main function of the program
int main() {
int p, q, r;
// Step-1 Take inputs from the user
cout << "Enter two integer values::\n";
cin >> p >> q;
// Step-2 Calculating the sum of input numbers
r = p + q;
// Step-3 Final output of the program
cout << "Result:: " << p << " + " << q << " = " << r << endl;
return 0;
}
Output
Enter two integer values::
5
7
Result:: 5 + 7 = 12
Example-2 Using the minimal variables
// C++ program to find the sum of two integers with minimum variables
#include <iostream>
using namespace std;
// It's the main function of the program
int main() {
int p, q;
// Step-1 Take inputs from the user
cout << "Enter two integer values::\n";
cin >> p >> q;
cout << "Result:: " << p << " + " << q << " = ";
// Step-2 Calculating the sum of input numbers
p = p + q;
// Step-3 Final output of the program
cout << p << endl;
return 0;
}
Output
Enter two integer values::
90
30
Result:: 90 + 30 = 120
Example-3 Using the Real values
// C++ program to find the sum of two real numbers
#include <iostream>
using namespace std;
// It's the main function of the program
int main() {
float p, q;
// Step-1 Take inputs from the user
cout << "Enter two float values::\n";
cin >> p >> q;
cout << "Result:: " << p << " + " << q << " = ";
// Step-2 Calculating the sum of input numbers
p = p + q;
// Step-3 Final output of the program
cout << p << endl;
return 0;
}
Output
Enter two float values::
5.23
7.29
Result:: 5.23 + 7.29 = 12.52