Sum of Two Numbers

Sum of Two Numbers in C++

Handling user input is a vital skill for any programmer. This exercise teaches you how to sum two numbers in C++ provided by the user, exploring variables, cin, and basic arithmetic.

Understanding Input/Output Streams

std::cin

The standard input stream in C++. It uses the extraction operator >> to capture data from the keyboard and store it in variables.

Variable Declaration

We use int to define integer variables like num1 and num2, which reserve memory space for the user's data.

Arithmetic Addition

The + operator processes the values stored in variables to calculate a result, which is then assigned to a third variable.

Pro Tip: Data Types

While this example uses int (integers), you can use float or double if you want to sum numbers with decimals (e.g., 5.5 + 4.2).

Learning Objectives

  1. Declare multiple integer variables.
  2. Implement cout to prompt the user.
  3. Use cin to read keyboard data.
  4. Perform and display a basic addition operation.

C++ Sum of Two Numbers Code

sum_numbers.cpp C++ Beginners
#include <iostream>
using namespace std;

int main() {
    int num1, num2, sum; // Variable declaration

    cout << "Enter the first number: ";
    cin >> num1; // Capture first input

    cout << "Enter the second number: ";
    cin >> num2; // Capture second input

    // Basic arithmetic addition
    sum = num1 + num2;

    cout << "The sum is: " << sum << endl;

    return 0;
}

Program Console Output:

Enter the first number: 7
Enter the second number: 5
The sum is: 12
User Input & Arithmetic Logic
User Input (std::cin) Data Types & Variables Arithmetic Operators Memory Allocation Basics Data Output (std::cout) Input Streams IPO Programming Model Assignment Statements

Share this C++ Exercise

Help other students master C++ input/output streams.

© C++ Programming Exercises. Master the art of performance coding.