Here are a few ways to implement a function that adds one to $i$ and jumps back to $0$ after reaching $n$. I've chosen to write these in the C programming language, but they should be easy to port to other imperative languages.
This is probably the most straightforward way to accomplish the task:
int add_one_upto_n (int i, int n) { if (i >= n) return 0; else return i + 1; }
Alternatively, we can use the C divide-and-take-remainder operator %
. This will work nicely on modern desktop CPUs, but may be inefficient on simple embedded systems where division is slow:
int add_one_upto_n (int i, int n) { return (i + 1) % (n + 1); }
Also, if $n$ happens to equal $2^k-1$ for some $k$, the %
operator may be replaced with a simple bitwise and operation:
int add_one_upto_n (int i, int n) { return (i + 1) & n; /* only works if n + 1 is a power of 2 */ }
I think that about exhausts all the reasonable ways to do it I could think of. Of course, if we get into the realm of deliberately obfuscated code, I'm sure there are many more creative ways to accomplish this task...