Paul's answer shows how to do recursion. However, a function that takes only two arguments (the number of cycles and the maximum value) does not have enough context for the actual printing of numbers, as in your example. To do this, you will need to track additional information. One way to do this:
void _print_loop(int *values, int width, int cur_col, int max) { if (cur_col == width) { for (int i = 0; i < width; i++) { printf("%d%c", values[i], (i < width - 1) ? ' ' : '\n'); } } else { for (int i = 0; i < max; i++) { values[cur_col] = i; _print_loop(values, width, cur_col + 1, max); } } } void print_loop(int width, int max) { int values[width]; memset(values, 0, width * sizeof(int)); _print_loop(values, width, 0, max); }
Now print_loop(3, 2) behaves as expected.
Edit: to do this, you can write a function with two arguments, using static variables that are initialized after receiving a positive width argument. After this initialization step, the function performs its recursion using negative values. Obviously, the resulting code is terrible, but I will still send it for completeness:
void print_loop(int width, int max) { static int max_width; static int *values; if (width > 0) { max_width = width; if ((values = calloc(width, sizeof(int))) == NULL) { perror("calloc"); exit(EXIT_FAILURE); } print_loop(-width, max); free(values); } else if (width == 0) { for (int i = 0; i < max_width; i++) { printf("%d%c", values[i], (i < max_width - 1) ? ' ' : '\n'); } } else { for (int i = 0; i < max; i++) { values[-width - 1] = i; print_loop(width + 1, max); } } }
Stephan202
source share