Google News
logo
C++ Program to Add Two Numbers
In the following example of C++ program that adds two numbers and prints the result to the console :
Program :
#include <iostream>

int main() {
    int num1, num2, sum;
    std::cout << "Enter first number: ";
    std::cin >> num1;
    std::cout << "Enter second number: ";
    std::cin >> num2;
    sum = num1 + num2;
    std::cout << "Sum of " << num1 << " and " << num2 << " is " << sum;
    return 0;
}
Output :
Enter first number: 7
Enter second number: 9
Sum of 7 and 9 is 16
* This program declares three variables : num1, num2, and sum, which are all of type int.

* The program then prompts the user to enter two numbers using the std::cout and std::cin objects from the iostream library.

* The >> operator is used to input the user's numbers into the variables num1 and num2.

* The program then adds the two numbers and assigns the result to the sum variable. Finally, the program uses std::cout to output a message that displays the sum of the two numbers to the console.