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).
Core Programming Concepts:
- cin: Captures user input efficiently.
- Variables: Named storage locations for data.
- cout: Outputs the final result to the console.
Learning Objectives
- Declare multiple integer variables.
- Implement
coutto prompt the user. - Use
cinto read keyboard data. - Perform and display a basic addition operation.
C++ Sum of Two Numbers Code
#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