Sum of Two Numbers in C++

Add two integers in C++ and print the sum. Watch int overflow and failed cin.

BeginnerBasic ProgramsExample 4 of 14
sum-of-two-numbers.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int num1, num2, sum;
6
7 cout << "Enter first number: ";
8 cin >> num1;
9
10 cout << "Enter second number: ";
11 cin >> num2;
12
13 sum = num1 + num2;
14
15 cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;
16
17 return 0;
18}

Output

Enter first number: 10
Enter second number: 20
Sum of 10 and 20 is: 30

What's going on

This C++ program reads two integers, adds them, and prints the sum. The + is the easy part.

#include <iostream>

cout and cin.

int num1, num2, sum;

Three ints. Until cin fills the first two, don't add them. int num1 = 0, num2 = 0; is cheaper than printing garbage after a failed read.

cout << "Enter first number: ";

cin >> num1;

Then the same for num2. You could write cin >> num1 >> num2 with one prompt. Two prompts match the sample output.

Letters make extraction fail. cin sets failbit and leaves the variable alone. If it was uninitialized, the sum is nonsense.

sum = num1 + num2;

Sample: 10 + 20 = 30. That's what the page prints.

int overflow is silent. 2000000000 + 2000000000 wraps to a negative (or some other two's-complement value). If the problem allows values near 10^18, use long long.

cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;

Prints the inputs and the result. Failed input and overflow are the bugs worth remembering, not the plus sign.