Add two numbers using ++ operator in C++.



Adding two numbers is a basic arithmetic operation, where we simply combine their values to get the total. The given task is to add two numbers using the "++" operator in C++.

Let's understand this with an example:

Scenario 1

// Adding two numbers using '+' operator
Input: a = 7, b = 3  
Output: 10 
Explanation:
a + b => 7 + 3 = 10

Scenario 2

// Adding two numbers using '++' operator
Input: a = 7, b = 3  
Output: 10 
Explanation:
a + b => 7 + 1 + 1 + 1 = 10
(we increase 'a' 3 times because the second number 'b' is 3). 

Adding Two Numbers Using the "++" Operator

The ++ operator is a unary increment operator, i.e., it operates on a single variable. It increases the value of a variable by 1. For example, if x is 3, then x++ will make it 4.

The idea is that we can increase the value of the first number as many times as the value of the second number using "++" to get the sum, to achieve this:

  • Start a for loop with 0 as the initial value and the secondNumber as the end value. 
  • Within the loop, increment the first number.

Example

In the following C++ program, we are adding two numbers using the "++" operator:

#include <iostream>
using namespace std;

int main() {
   int firstNumber = 10, secondNumber = 5;    
   // Add secondNumber to firstNumber using only ++ operator
   for (int i = 0; i < secondNumber; i++) {
       firstNumber++;
   }
   cout<<"First number is: "<< firstNumber <<endl;
   cout<<"Second number is: "<<secondNumber <<endl;
   cout << "Sum = " << firstNumber << endl;
   return 0;
}

Following is the output of the above program:

First number is: 15  
Second number is: 5  
Sum = 20

Conclusion

In this article, we have learned how to add two numbers using the ++ operator by incrementing one number repeatedly. This method is simple and easy to understand.

Updated on: 2025-07-25T12:41:43+05:30

834 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements