Indeed we can use recursion to build the n
-levels deep structure of the nested for
loops, performing the action at the deepest level of recursion.
Or, equivalently, we can build n-1
levels and perform the last for
loop explicitly, like this:
#include <stdio.h>
void rec(const char *pre, int n, int lo, int hi) {
if (n == 0) return;
if (n > 1) {
for (int k = lo; k <= hi; k++) {
char tmp[100]; // 100 is enough for home use
sprintf(tmp, "%s %d", pre, k);
rec(tmp, n - 1, k + 1, hi);
}
} else {
for (int k = lo; k <= hi; k++) printf("%s %d\n", pre, k);
}
}
int main(void) {
rec("", 3, 0, 5); // use 3 values from 0 to 5
return 0;
}
This creates sorted triplets of numbers in the 0..5 range. Output
0 1 2
0 1 3
0 1 4
0 1 5
0 2 3
0 2 4
0 2 5
0 3 4
0 3 5
0 4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
Replacing the call in main
with rec("", 4, 0, 5);
creates 4-tuples; the output is
0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
Added my thought process to write the recursive function
I know a recursivity solution is based on "reduce complexity and recurse". So I want to "solve" n
loops when I know how to do n-1
loops.
But I don't know how t do n - 1
loops!
Wait... I know how to 0
loops. It's easy (but not helpful): just do nothing
if (n == 0) return;
I also know how to do 1
loop. Just print the numbers
if (n == 1) for (int k = lo; k <= hi; k++) printf("%d ", k);
This is good. Can be used to do n
loops.
How to do n
loops?
For each available number, save the number and recurse with 1
less loop and adjusted limits.
It was this that generated that code. After writing the code I could have studied it attentively and stream line some aspects, but decided to post as it was.