In this article, we will learn how to add two numbers using the C++ programming language. We will accept two numbers from the user and perform the addition operation. Once we have the results we will display them on the output screen.
C++ Program to Add Two Numbers
#include <iostream>
using namespace std;
int main()
{
int num1, num2, sum = 0;
cout << "Please enter two numbers for addition: ";
cin >> num1 >> num1;
sum = num1 + num2;
cout << "The Sum of addition of "<< num1 << " + " << num2 << " = " << sum;
return 0;
}
Output:
Please enter two numbers for addition: 5
9
The Sum of addition of 5 + 9 = 14
- 6 ways to Reverse Array in C++
- How to Find Max Value in C++ Array
- How to Find Minimum Value in C++ Array
- Different ways to Declare arrays in C++
- Create Pointer arrays in C++ dynamically
- Different ways to Declare arrays of strings in C++
- Loop through Array in C++
- 6 Ways to Find Size of Array in C++
- How to return an Array From a Function in C++
C++ Program to Add Five Numbers
In our next example, we are going to learn how we can expand our first program of adding two numbers to the addition of five numbers. This is similar to above program, only difference we have here is we are taking input from user by using a for loop.On each input we add the number to the commulative sum.This way when user enters the last 5th number, we have the sum ready to display.
C++ Program to Add Five Numbers
#include <iostream>
using namespace std;
int main()
{
int numbers, sum = 0;
cout << "Please enter 5 numbers to add: " << endl;
for (int i = 0; i < 5; i++)
{
cin >> numbers;
sum = sum + numbers;
}
cout << "The Sum of the 5 numbers is: " << sum << endl;
return 0;
}
}
Output:
Please enter 5 numbers to add:
1
2
3
4
5
The Sum of the 5 numbers is: 15