ekaf ekaf - 4 months ago 17
C Question

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

Answer
#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