In order to vary the number of "nested loops" you need to use recursion.
void printCombination(string[] str, string partial, int p) {
if (p == str.Length) {
Console.WriteLine(partial);
return;
}
for (int i = 0 ; i != str[p].Length; i++) {
printCombination(str, partial + str[p][i], p+1);
}
}
Initial call looks like this:
printCombination(new[] {"ab", "cd", "ef", "gh"}, "", 0);
EDIT (in response to a comment by OP)
To understand what is going on, you need to understand the meaning of the parameters first:
str
is the array of strings. Each element of the array corresponds to a nesting level of the imaginary nested loops: element 0 is for the outer loop, element 1 is for the first level of nesting, and so on.
partial
is the partially constructed result string. It is empty at the initial level, has one character at the first level of nesting, two at the second, and so on.
p
is the nesting level. It is zero in the initial level, one at the first nesting level, and so on.
The function has two parts - the stopping condition, and the body of the recursive call. The stopping condition is simple: once we get to the last level, partial
result is no longer "partial": it is complete; we can print it out and exit. How do we know that we're at the last level? The number of elements of str
equals the number of levels, so when p
equals the length of the str
array, we're done.
The body of the recursive call is a loop. It does the same thing that your nested loops do, but for only one level: each iteration adds one letter from its own array, and calls itself recursively for the next level.
The best way to see this in action is to set a breakpoint on the line with the return
statement, and look at the call stack window . Click each invocation level, and inspect the values of function parameters.
If you are up for an exercise, try modifying this function to take two parameters instead of three. Hint: you can eliminate the last parameter by observing that the length of partial
always matches the value of p
.