0

I have been given a task to add and subtract two int variables WITHOUT using the built in operators (+ and -) and instead using the increment and decrement operators. How do I go about doing this?

    int add1;
    int add2; 
    int total;

    cout << "Please enter the 2 numbers you wish to add" << endl;
    cin >> add1;
    cin >> add2;

    //perform addition using increment operators

    return 0;

thanks for the help!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Moojave
  • 37
  • 2
  • 7

3 Answers3

4

Use a for loop.

e.g.

 for (; add1; add1--, add2++);

add2 will be add1 + add2 assuming add1 is positive

Similar idea for subtraction

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
2

It is obvious that you need to use either loops or recursive functions. For example

int add1;
int add2;
cout << "Please enter the 2 numbers you wish to add" << endl;
cin >> add1;
cin >> add2;

int sum = add1; 
for ( int i = 0; i < add2; i++ ) ++sum;

int diff = add1; 
for ( int i = 0; i < add2; i++ ) --diff;

std::cout << "sum is equal to: " << sum << std::endl;  
std::cout << "difference is equal to: " << diff << std::endl;  

return 0;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

You have to use some sort of built in operators to perform this unless you are required to write a token parser and create your own interpreter and compiler. But I'm guessing since the question is quite basic, it's not asking you to do that.

You can simply do this:

int add1;
int add2;
cout << "Please enter the 2 numbers you wish to add" << endl;
cin >> add1;
cin >> add2;

//perform addition using increment operator
cout << (add1 += add2);

return 0;

EDIT - added decrement operator with less than or equal to 0 if/else:

int add1;
int add2;
int sub1;
int sub2;

cout << "Please enter the 2 numbers you wish to add" << endl;
cin >> add1;
cin >> add2;

//perform addition using increment operator
cout << (add1 += add2);

cout << "Please enter the 2 numbers you wish to subtract" << endl;
cin >> sub1;
cin >> sub2;

if((sub1 - sub2) <= 0)
{
    cout << "Number is less than or equal to 0." << endl;
}
else
    cout << (sub1 -= sub2);


return 0;
Element808
  • 1,298
  • 11
  • 20
  • Remember, there's no reason to make it overly complicated. If you want to try a for loop to get this done then it's fine but, in my opinion, it's overdoing it for the task. As a programmer, not only is your job to solve problems, but to solve them in the best possible way. – Element808 Feb 19 '14 at 19:37