OneBite.Dev - Coding blog in a bite size

Add Two Numbers In C++

Code snippet for how to Add Two Numbers In C++ with sample and detail explanation

C++ is a powerful and versatile programming language that allows for complex programming tasks, including ones as simple as adding two numbers together. By using the basic functions and syntax of the C++ language, we can design a program that accomplishes this task.

Code Snippet For Adding Two Numbers

#include<iostream>
using namespace std;

int main() {
    int num1, num2, sum;
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    sum = num1 + num2;
    cout << "The sum is: " << sum;
    return 0;
}

Code Explanation For Adding Two Numbers

Step 1: We start off by including the necessary headers, we use #include<iostream> which is necessary for input/output operations in C++. “using namespace std” is used so that we do not need to include the keyword “std” before each C++ statement.

Step 2: Then we define the main function which is the entry point of any C++ program, “int main()“.

Step 3: We go ahead to declare our variables; “int num1, num2, sum”. Here, ‘num1’ and ‘num2’ are the numbers entered by the user and ‘sum’ is the variable to store the sum of ‘num1’ and ‘num2’.

Step 4: We output a prompt message to the user to enter two numbers with the statement “cout << “Enter two numbers: ”;“.

Step 5: Then, we get the user input with the “cin” keyword and store those inputs in the variables ‘num1’ and ‘num2’ respectively. “cin >> num1 >> num2” gets the two numbers from the user.

Step 6: Subsequently, we calculate the sum of the two numbers and store it in the ‘sum’ variable. The code “sum = num1 + num2;” adds the numbers.

Step 7: Finally, we output the result with “cout”, the ”<<” operator is a type of insertion operator in C++. The line “cout << “The sum is: ” << sum;” will print “The sum is: ” and the result of the sum to the console.

Step 8: We return an integer using “return 0”. This line of code is declaring that the program has executed successfully. In C++, returning ‘0’ from the ‘main’ function indicates that the program has executed successfully.

c-plus-plus