mod 12 addition/subtraction

Feb 14, 2009 at 8:04pm
I'm using the following code to do some addition and subtraction, mod 12. [Maybe I'm using the wrong mathematical term, but this does not seem to correspond to the "modulus" operator (%x), which calculates the remainder when divided by x.] Think of addition as moving clockwise on a clock face, and subtraction as moving counter-clockwise. 5+8=1, 5-8=9...

//This program adds and substracts two integers together, mod12.

#include <iostream>

using namespace std;

main ()
{
int x;
int y;
int sum;
int difference;

cout << "Enter an integer, 0-11: " << endl;
cin >> x;
cout << "Enter another integer, 0-11: " << endl;
cin >> y;
sum = x+y;
if (sum > 11) // "corrects" for mod12 addition
{
sum = sum - 12;
}
difference = x-y;
if (difference < 0) // "corrects" for mod12 subtraction
{
difference = difference + 12;
}
cout << x << "+" << y << "=" << sum << endl;
cout << x << "-" << y << "=" << difference;

return(0);
}

My question is this:
Is there a better way to do this than by using the "if" statements I've used here?

Thanks!
Feb 15, 2009 at 1:40pm
That is exactly the % (modulo) operator.

( 5 + 8 ) % 12 == 1.

Subtraction is different because of the negative. If a < b then a - b is negative, but

( 12 + a - b ) % 12 == ( a - b ) % 12.

Feb 15, 2009 at 2:52pm
Thanks for the help! I don't get it -- I swear that I tried those very equations and didn't get correct answers, but today it works. I must have typed something wrong, thought I'm not sure what.

Thanks again.
Topic archived. No new replies allowed.