Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Add Two Numbers in C++

Read two integers and print their sum in C++, declaring the result right where it is computed. A short practice drill on cin, + and the type limits of int.

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

Sample Output

Sum of 15 and 27 = 42

Inputs and their sum.

In this one

  • How to declare a variable at the point where you need it
  • How cin fills two integers in turn
  • How the result is printed with a custom message
  • When to switch from int to long long

How it works

  1. 1

    Declare num1 and num2.

  2. 2

    Read 15 and 27 from the keyboard.

  3. 3

    Declare and set int sum = num1 + num2 = 42.

  4. 4

    Print the formatted result.

Edge cases

Negative numbers

Enter -5 and 3.

int handles negatives, so the sum is -2. Nothing special is needed.

Extra input on the line

Type 15 27 99 at the first prompt.

num1 gets 15, num2 gets 27 straight from the buffer without waiting, and 99 stays unread. The second prompt still prints, which can look odd.

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).

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does int sum = num1 + num2; do?

Pick an answer to check it.

Question 2

Which input causes undefined behavior here?

Pick an answer to check it.

Questions people ask

How is this different from Sum of Two Numbers?

The logic is the same. Here sum is declared at the moment it is calculated, and the output uses = instead of is:.

Where should I declare variables?

Modern style declares them as close to first use as possible, which keeps their purpose obvious.

How do I add more than two numbers?

Use a loop and a running total, as in the Sum of n Natural Numbers program.