How to use the Increment and Decrement Operators In C++

Here use the increment/decrement operator to add two numbers. Decrement a number by one till it becomes zero and increment another number by one, return the second number.

while(B > 0){ 
    A++; 
    B--; 
}

C++ Program to Add Two Numbers Using the Increment and Decrement Operators

C++




// C++ program to add two number using
// increment/decrement operator
#include <iostream>
using namespace std;
  
// Function to return sum
// of two number
int addTwoNumber(int A, int B)
{
    // When A is positive
    while (A > 0) {
        A--;
        B++;
    }
  
    // When A is negative
    while (A < 0) {
        A++;
        B--;
    }
  
    // Return sum of A and B
    return B;
}
  
// Driver Code
int main()
{
    // Given two number
    int A = 4, B = 11;
  
    // Function call
    cout << "sum = " << addTwoNumber(A, B);
    return 0;
}


Output

sum = 15
  • Time Complexity: O(N), where N is the min(A,B)
  • Auxiliary Space: O(1)

Add Two Numbers in C++

The addition of two numbers is a simple task in C++ that can be done using the arithmetic addition operator (+). But there are many other ways to find the sum of two numbers in C++. In this article, we will discuss 7 different ways to add two numbers in C++.

Similar Reads

1. Using Addition Operator

Here simply use the addition operator between two numbers and print the sum of the number....

2. Using the Subtraction Operator

...

3. Using the Increment and Decrement Operators

Here simply use the subtraction operator between two numbers, two times so that minus-minus multiplies and produce the + operator, and return the sum of the numbers....

4. Using printf() method

...

5. Using Half Adder Method

Here use the increment/decrement operator to add two numbers. Decrement a number by one till it becomes zero and increment another number by one, return the second number....

6. Using Exponential and Logarithm

...

7. Using Recursion

Here “%*s” specifier print the value of a variable, the value of the variable times, and printf() method return how many character print on the screen....