C++ program to add two numbers

1. Introduction

In the realm of programming, starting with the basics is crucial. Simple operations form the foundation upon which more advanced concepts are built. One such foundational task is the addition of two numbers. In this blog post, we will dive into a C++ program to add two numbers and understand the ins and outs of it.

2. Program Overview:

The program will work as follows:

1. Declare variables to hold the two numbers and their sum.

2. Prompt the user for input.

3. Compute the sum of the entered numbers.

4. Display the result.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    // Declare variables
    double num1, num2, sum;

    // Prompt user for the first number
    cout << "Enter the first number: ";
    cin >> num1;

    // Prompt user for the second number
    cout << "Enter the second number: ";
    cin >> num2;

    // Compute the sum
    sum = num1 + num2;

    // Display the result
    cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;

    return 0;   // Signifies successful program termination


Enter the first number: 5
Enter the second number: 7
The sum of 5 and 7 is: 12

4. Explanation

Here's a step-by-step breakdown of the program:

1. The program starts by including the iostream library, which will allow us to handle input and output operations.

2. We declare three variables: num1, num2, and sum. These will store our two numbers and their sum, respectively.

3. We use the cout function to prompt the user for the first number and the cin function to store their input in num1.

4. Similarly, we prompt the user for the second number and store it in num2.

5. Next, we add the two numbers together and store the result in the sum variable.

6. We then display the result using cout, presenting the user with the sum of the two numbers they entered.

7. The program concludes with a return statement, which signifies its successful execution and termination.