16,001,979 members
See more:
I want to make a circular counter in C programming. First variable can store value from 0-3. Second variable asks the value from user (from 0-3). Third variable asks user to move either left or right

If third variable is left the second variable should move left:

3->2
2->1
1->0
0->3
Similarly if third variable is right the second variable should move right:

0->1
1->2
2->3
3->0

What I have tried:

ii have tried modulus ,but its not working on edges
Posted
Updated 6-Aug-16 1:05am
OriginalGriff 6-Aug-16 5:23am
This is not a good question - we cannot work out from that little what you are trying to do.
So perhaps if you show us what you tried, the values you fed it and both the results you got an those you expected it might help.
Use the "Improve question" widget to edit your question and provide better information.
Patrice T 6-Aug-16 7:32am
Show the code that is not working. I know for sure modulus works.

## Solution 2

Quote:
ii have tried modulus ,but its not working on edges

You mention only "..., but ist not working in edges", but you don't describe what is not working i.e. what you expect and what you get.

My guess is, you don't get the right value for 0->3, because you make something like this: `(0 - 1) % 4` and you expect 3, but get -1.

Why -1 % 4 == -1 you can find in the literature, i.e. Modulo operation - Wikipedia, the free encyclopedia[^]

For you the trick to correct this is:
C#
```const int cRange= 4;
int position;  // defined and set anywhere in your program..
int direction; // will be +1 or -1, defined and set anywhere in your program..
position= (Position + direction + cRange) % cRange;```

Finally for Position == 0 and direction is -1:
(0 - 1 + 4) % 4 => 3
or Position = 3 and direction is + 1:
(3 + 1 + 4) % 4 => 0
I hope it helps.

v3