Adding of two numbers using minus (-) operator in C/C++

Here, we are going to learn how we can two numbers using minus (-) operator in C/C++ program?
Submitted by IncludeHelp, on June 03, 2020

Given two numbers, and the task is to find their addition using the minus (-) operator.

As we have discusses in C/C++ arithmetic operators that plus (+) operator adds the numbers and minus (-) operator subtracts the numbers. But adding two numbers using minus (-) operator can also be done – It's a simple mathematical trick.

As we know that, minus and minus becomes plus. Thus, to add two numbers – we can subtract the negative of the second number from the first number.

first_number - (-second_number)

Example:

Input:
x = 10
y = 20

Operation:
result = x - (-y)

Output:
result = 30

Program:

#include <iostream>
using namespace std;

int main()
{
    int x = 10;
    int y = 20;

    // printing the numbers
    cout << "x : " << x << endl;
    cout << "y : " << y << endl;

    // calculation
    int result = x - (-y);

    // printing the result
    cout << "result : " << result << endl;
    cout << endl;

    // assigning the other values
    x = -10;
    y = 20;

    // printing the numbers
    cout << "x : " << x << endl;
    cout << "y : " << y << endl;

    // calculation
    result = x - (-y);

    // printing the result
    cout << "result : " << result << endl;
    cout << endl;

    // assigning the other values
    x = -10;
    y = -20;

    // printing the numbers
    cout << "x : " << x << endl;
    cout << "y : " << y << endl;

    // calculation
    result = x - (-y);

    // printing the result
    cout << "result : " << result << endl;

    return 0;
}

Output:

x : 10
y : 20
result : 30 

x : -10 
y : 20
result : 10 

x : -10 
y : -20 
result : -30



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.