write a code that adds two number
#include <iostream>
int main() {
int num1, num2, sum;
// Prompt the user to enter the first number
std::cout << "Enter the first number: ";
std::cin >> num1;
// Prompt the user to enter the second number
std::cout << "Enter the second number: ";
std::cin >> num2;
// Add the two numbers
sum = num1 + num2;
// Display the sum
std::cout << "The sum of " << num1 << " and " << num2 << " is " << sum << std::endl;
return 0;
}
Explanation:
1. We include the <iostream>
header file, which allows us to use the input/output stream objects in C++. This header file provides the functionality to read input from the user (std::cin
) and display output to the console (std::cout
).
2. We define the main()
function, which is the entry point of our program. The program execution starts from this function.
3. Inside the main()
function, we declare three integer variables: num1
, num2
, and sum
. These variables will be used to store the two numbers to be added and their sum, respectively.
4. We use the std::cout
object to prompt the user to enter the first number. The <<
operator is used to insert the text into the output stream.
5. We use the std::cin
object to read the user's input and store it in the variable num1
. The >>
operator is used to extract the input from the input stream.
6. Similarly, we prompt the user to enter the second number and read it into the variable num2
using std::cin
.
7. We add the values of num1
and num2
and store the result in the variable sum
.
8. We use std::cout
to display the sum to the user. We use the <<
operator to insert the variables num1
, num2
, and sum
into the output stream. The <<
operator can be used to concatenate multiple values.
9. Finally, we return 0 from the main()
function, indicating successful program execution.