How to Adding Two Numbers in C++

Here’s a simple program to add two numb

#include <iostream>
using namespace std;

int main() {
    // Declare variables
    int num1, num2, sum;

    // Ask the user for input
    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;

    // Add the numbers
    sum = num1 + num2;

    // Display the result
    cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl;

    return 0;
}

 

Output:
Enter first number: 5
Enter second number: 7
The sum of 5 and 7 is 12

Explanation:

  1. Include header file: #include <iostream> allows us to use input and output streams.
  2. Using namespace: using namespace std; is used to avoid writing std:: before standard library names.
  3. Main function: int main() is the starting point of the program.
  4. Declare variables: int num1, num2, sum; declares three integer variables.
  5. Input numbers: cin >> num1; and cin >> num2; take input from the user.
  6. Add numbers: sum = num1 + num2; calculates the sum.
  7. Output the result: cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl; displays the result.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top