How to Implement a Circular Counter?

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
9

2 Answers

#include <stdio.h>

int main(void)
{
    int max = 3, num, i;

    num = 0;
    for (i = 0; i < 10; i++) {
        printf("%d\n", num);
        num = (num + 1) % (max + 1);
    }
    puts("--");
    num = max;
    for (i = 0; i < 10; i++) {
        printf("%d\n", num);
        num = (max - -num) % (max + 1);
    }
    return 0;
}

Output:

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

If you wrap at a power of two, then this technique will work.

#include <stdio.h>

typedef struct
{
    unsigned int x : 2;    /* Holds up to 4 values */

} SmallInt;


int main()
{
    SmallInt up   = {0};
    SmallInt down = {0};

    for (int z = 0; z < 10; z++)
    {
        printf("%d %d\n", up.x, down.x);

        up.x++;
        down.x--;
    }

    return 0;
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest