Sum of Two Numbers in C++
Add two integers read with cin and print the result in C++. A first-week lesson on input, the + operator, failed reads, and silent int overflow near 2 billion.
1#include <iostream>2using namespace std;34int main() {5 int num1, num2, sum;67 cout << "Enter first number: ";8 cin >> num1;910 cout << "Enter second number: ";11 cin >> num2;1213 sum = num1 + num2;1415 cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;1617 return 0;18}
Sample Output
Sum of 10 and 20 is: 30
The two inputs echoed back, then the computed sum.
In this one
- How to read two numbers with cin
- How to store the result of + in a variable
- Why an uninitialized int can print garbage
- When int overflows and long long is needed
How it works
- 1
Declare num1, num2, and sum as int.
- 2
Prompt and read num1, then prompt and read num2.
- 3
Compute sum = num1 + num2.
- 4
Print the inputs and the sum in one line.
Edge cases
Large inputs
Enter 2000000000 and 2000000000.
The true sum, 4000000000, does not fit in a 32-bit int (max 2147483647). Signed overflow is undefined behavior, and in practice you usually see a negative number. Use long long for big values.
Decimal input
Enter 2.5 for the first number.
cin reads 2 into num1 and leaves .5 in the buffer. The second read then fails because .5 cannot start an int, so the sum is wrong.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which type is safest for adding two numbers near 3 billion?
Pick an answer to check it.
Question 2
What does cin >> num1 do if the user types "abc"?
Pick an answer to check it.
Questions people ask
Can I read both numbers in one line?
Yes: cin >> num1 >> num2; The user can type 10 20 with a space or press Enter between them.
How do I add decimals?
Declare the variables as double instead of int. Then 2.5 + 1.25 prints 3.75.
What is the largest int?
On typical compilers int is 32 bits, so the largest value is 2147483647. long long goes up to about 9.2 × 10^18.