Add Two Numbers in C++
Given two integers, the task is to add these integer number and print their sum in C++.
Examples
Input: a = 11, b = 9
Output: 20
Explanation: Sum of 11 + 9 = 20Input: a = 1, b = 8
Output: 9
Explanation: Sum of 1 + 8 = 9
Add Two Numbers Using Addition Operator
In C++, the simplest method for adding the two numbers is using the addition operator(+). This operator adds the given two values and return their sum.
Code Implementation
// C++ program to add two number using
// addition operator
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 11, b = 9;
// Adding the two numbers and printing
// their sum
cout << a + b;
return 0;
}
Output
20
Time Complexity: O(1)
Auxiliary Space: O(1)
Table of Content
Other Methods for Adding Two Numbers in C++
Apart from addition operator, there are also the various methods by which we can add two integers.
Using Increment Operator (++)
We can also add two numbers in C++ using the increment operator by repeatedly increasing the first value to the number of times equal to second value using a loop.
Code Implementation
// C++ Program to add two numbers using
// increment operator
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 11, b = 9;
// If b is positive, increment a to b times
for (int i = 0; i < b; i++)
a++;
// If b is negative, decrement a to |b| times
for (int i = 0; i > b; i--)
a--;
cout << a;
return 0;
}
Output
20
Time Complexity: O(b), where b is the second number
Auxiliary Space: O(1)
Using Bitwise Operators
According to the Half Adder logic, sum of two bits can be obtained by using Bitwise XOR(^) and carry bit can be obtained by performing Bitwise AND(&) of two bits. We can extend this logic to integers that contains multiple bits.
Approach
- Read two integers from the user.
- Use the bitwise XOR (^) operator to add the numbers without considering the carry.
- Use the bitwise AND (&) operator to calculate the carry.
- Left shift the carry by one position to align it for the next bit addition.
- Repeat the process until there is no carry left.
Code Implementation
// C++ program to add two numbers by using
// Bitwise operator or Half Adder Method
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 11, b = 9, carry;
while (b) {
// Carry is AND of a and b
carry = a & b;
// Sum without carry is XOR of a and b
a = a ^ b;
// Carry is shifted by one so that it can be
// added in the next iteration
b = carry << 1;
}
cout << a;
return 0;
}
Output
20
Time Complexity: O(log b), where b is the second number.
Auxiliary Space: O(1)