Reputation: 37
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!
Upvotes: 0
Views: 3642
Reputation: 1308
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;
Upvotes: -1
Reputation: 310950
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;
Upvotes: 2
Reputation: 59997
Use a for
loop.
e.g.
for (; add1; add1--, add2++);
add2
will be add1 + add2
assuming add1 is positive
Similar idea for subtraction
Upvotes: 4