In this program, we will learn how to add two Numbers in C++ programming language.
To add two numbers in C++, we will ask the user to enter the two number and place the addition of the two number in sum variable of same type and print this variable in the output which is the sum of the two entered numbers as shown here in the following program.
Program to add two Integers
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> using namespace std; int main() { int a, b, sum; cout << "Enter first number: "; cin >> a; cout << "Enter second number: "; cin >> b; sum = a + b; cout <<"Sum of the numbers: " << sum << endl; return 0; } |
1 2 3 4 5 |
Enter first number: 45 Enter second number: 65 Sum of the numbers: 110 |
Program to add two decimal (float)
Just change the datatype of the variables in the above program to float.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> using namespace std; int main() { float a, b, sum; cout << "Enter first number: "; cin >> a; cout << "Enter second number: "; cin >> b; sum = a + b; cout <<"Sum of the numbers: " << sum << endl; return 0; } |
Output:
1 2 3 4 5 |
Enter first number: 27.86 Enter second number: 78.42 Sum of the numbers: 106.28 |