Question: The following code snippet will print every 4 character long combination (without repetition) of the elements of an array. 

```
for (int i = 0; i < len; i++)
    for (int j = i + 1; j < len; j++)
        for (int k = j + 1; k < len; k++)
            for (int l = k + 1; l < len; l++)
                printf("%c%c%c%c\n", arr[i], arr[j], arr[k], arr[l]); 

```

My problem is I don't know how to extend this to a general function (ie print every N character long combination). How can I make a function do the same thing but be called like this:

```
combinationPrint(array, numberOfForLoops); // With other params if needed

```

Answer: 
The recursive version of your function would work like this: 

```
void recur (char* arr, int i, int len, char *x, int k, int n) {
    if (k==n) {   // the last inner loop
        x[k]=0; 
        printf ("%s\n", x);
    }
    else {   
        for (int j=i+1; j<len; j++) { // recursive loop
            x[k]=arr[j];
            recur (arr, j, len, x, k+1, n);  // call recursion for an inner loop
        }
    }
}

```

In this recursion, `arr` and `len` correspond to your definition and n is the depth of the loops you want to achieve (4 in your non recursive version). 

The trick is to use a null terminated array of n+1 chars, that you keep across the recursion and build the string that you want to print at the last level. i is then the starting position of the loop and k is the current level of recursion. 

You would call this: 

```
recur (arr, -1, len, out, 0, 4 );

```

**[Online demo](http://ideone.com/FVIbbz)**
Well, instead of N loops - you just need one. Within this main loop you have to have just two inner loops for incrementing array of indices and for printing values:

```
int increment(int* index, int N, int len)
{
    for (int i = N - 1; i >= 0; --i)
    {
        ++index[i];
        if (index[i] < len)
            return 1;
        index[i] = 0;
    }
    return 0;   
}

```

So - the main loop:

```
    int index[N] = {};

    do
    {
        // print
        for (int i = 0; i < N; ++i)
            printf("%c", arr[index[i]]);
        printf("\n");
    } while (increment(index, N, len));

```