C++ Program to Add Two Numbers

Updated on December 11, 2024
Add two numbers header image

Introduction

Adding two numbers is one of the fundamental operations in programming and serves as a great introduction to the syntax and arithmetic operations of a language like C++. Simple yet essential, this operation involves using basic mathematical operators to manipulate data, which can be represented in various data types.

In this article, you will learn how to create a C++ program to add two integers and then extend this to handle floating-point numbers. Discover how to prompt user input, perform the addition, and display the results.

Adding Two Integers

Example of Integer Addition

  1. Start by including the necessary headers. In this case, include <iostream> for input and output operations.

  2. Declare two integer variables to store the numbers to be added.

  3. Prompt the user to enter two integer values.

  4. Perform the addition and store the result.

  5. Output the result to the console.

    cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        int num1, num2, sum;
        cout << "Enter two integers: ";
        cin >> num1 >> num2;
        sum = num1 + num2;
        cout << "Sum = " << sum << endl;
        return 0;
    }
    

    In this code, cin is used to capture user input, and cout is used to print the output. The integers num1 and num2 are added, and their sum is stored in the variable sum which is then printed.

Adding Floating-Point Numbers

Example of Float Addition

  1. Begin by including the <iostream> header for handling input and output.

  2. Declare two float variables to hold the numbers for addition.

  3. Prompt the user for two floating-point numbers.

  4. Execute the addition and store the result in a float variable.

  5. Display the result.

    cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        float num1, num2, sum;
        cout << "Enter two floating-point numbers: ";
        cin >> num1 >> num2;
        sum = num1 + num2;
        cout << "Sum = " << sum << endl;
        return 0;
    }
    

    This snippet functions similarly to the integer example but uses float for decimal numbers. The cin object reads the floating-point numbers entered by the user, and cout prints the sum.

Conclusion

Adding numbers in C++ is a straightforward process that requires only basic programming skills. Whether dealing with integers or floating-point numbers, the approach remains similar: prompt for user input, perform arithmetic operations, and print the output. By mastering simple operations like this, you build a strong foundation for tackling more complex programming tasks in C++. Use these examples to effectively manage user input and arithmetic in your future C++ projects.