Add Two Numbers in C++
Add two numbers in C++ with cin and cout.
BeginnerBasic ProgramsExample 14 of 14
add-two-numbers.cpp
1#include <iostream>2using namespace std;34int main() {5 int num1, num2;67 cout << "Enter first number: ";8 cin >> num1;910 cout << "Enter second number: ";11 cin >> num2;1213 int sum = num1 + num2;1415 cout << "Sum of " << num1 << " and " << num2 << " = " << sum << endl;1617 return 0;18}
Output
Enter first number: 15 Enter second number: 27 Sum of 15 and 27 = 42
What's going on
This C++ program reads two integers, adds them, and prints the sum. Same idea as Sum of Two Numbers — slightly different cout text.
int num1, num2;
Declared here. sum is declared later, right where it's computed. Both styles compile.
cin >> num1; then cin >> num2;
Sample: 15 and 27.
int sum = num1 + num2;
15 + 27 = 42. That's the output.
Failed cin leaves whatever was in the variables. Overflow on int is still silent. long long if the problem's limits need it.
If you're here after Sum of Two Numbers, the lesson is the pattern, not a new operator. Next useful fork is even/odd (%) or swap (three assignments).