Sum of Two Numbers

Beginner-friendly C++ program that teaches how to take two numbers from the user, add them, and display the result.

C++Beginner
C++
#include <iostream>
using namespace std;

int main() {
    int num1, num2, sum;
    
    cout << "Enter first number: ";
    cin >> num1;
    
    cout << "Enter second number: ";
    cin >> num2;
    
    sum = num1 + num2;
    
    cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;
    
    return 0;
}

Output

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

Sum of Two Numbers in C++

This program teaches you how to take two numbers from the user, add them together, and display the result. It is one of the most common and simplest programs for beginners learning arithmetic operations in C++.

1. Header File

We start with:

#include <iostream>

This header allows us to use:

  • cout → to display messages
  • cin → to take input from the user

Without this header, the program cannot perform input and output.

2. using namespace std;

This line lets us use cout and cin without writing std::cout or std::cin.
It makes the code simpler to read and write.

3. Declaring Variables

Inside the main function, we have:

int num1, num2, sum;

This line creates three integer variables:

  • num1 → stores the first number
  • num2 → stores the second number
  • sum → stores the result of num1 + num2

The data type int means these variables can hold whole numbers (positive or negative).

4. Taking Input From the User

To get input from the user, we use cin.

First:

cout << "Enter first number: ";
cin >> num1;

The program prints a message asking for the first number.
The user types a number (like 10), and cin stores it in num1.

The same thing happens for the second number:

cout << "Enter second number: ";
cin >> num2;

Now num2 holds the second number typed by the user (like 20).

5. Adding the Two Numbers

Next, the program performs the addition:

sum = num1 + num2;

This calculates the total of num1 and num2, and stores the result in sum.

If num1 = 10 and num2 = 20, then: sum = 30

6. Displaying the Result

The final output line is:

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

This prints a complete message showing the two numbers and their sum.

So the final output becomes:

Sum of 10 and 20 is: 30

endl moves the cursor to the next line.

7. return 0;

This ends the program and tells the computer that everything ran successfully.

Summary

  • The program reads two integers from the user.
  • It adds the numbers using the + operator.
  • The result is stored in a variable called sum.
  • The final message clearly shows the result to the user.

This exercise helps beginners understand variables, input/output, and simple arithmetic in C++. These skills are used in almost every program you write later.