Click here to Skip to main content
16,001,979 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Comments
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.
Remember that we can't see your screen, access your HDD, or read your mind.
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.

1 solution

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.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900