How can I limit the value of a variable?

In the following code j is supposed to take the values {0,3,6,1,4,7,2,5,8} sequentially for n=3. But (j%(n*n-1) part makes it 0 when it should be 8. Any way to solve this?

1
2
  for(int i=0, j=0; i<n*n; i++, j+=n)
      *(p1+i)=*(p2+(j%(n*n-1));
The serie looks like it could be from:
0 = 0 + 0 * 3
3 = 0 + 1 * 3
6 = 0 + 2 * 3
1 = 1 + 0 * 3
4 = 1 + 1 * 3
...

If so, think about i / n and i % n
Last edited on
@keskiverto
Thanks. That seems to work.
Last edited on
Topic archived. No new replies allowed.