C++ program to add two numbers:
#include <iostream>
using namespace std;
int main() {
// Declare variables to store the numbers
int num1, num2;
// Prompt the user to enter the first number
cout << "Enter the first number: ";
cin >> num1;
// Prompt the user to enter the second number
cout << "Enter the second number: ";
cin >> num2;
// Calculate the sum
int sum = num1 + num2;
// Display the result
cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;
return 0;
}
Explanation:
1. We include the `<iostream>` header to use input/output operations.
2. We use the `using namespace std;` directive to avoid writing `std::` before standard functions like `cout` and `cin`.
3. We declare two integer variables `num1` and `num2` to store the input numbers.
4. We prompt the user to enter the first number using `cout` and get the input using `cin`.
5. Similarly, we prompt the user to enter the second number and get the input.
6. We calculate the sum of the two numbers and store it in the `sum` variable.
7. Finally, we display the result using `cout`.
Output:
Enter the first number: 10
Enter the second number: 20
The sum of 10 and 20 is: 30
In this example, the user inputs `10` as the first number and `20` as the second number. The program then calculates the sum (`10 + 20 = 30`) and displays the result.