Nesting "for" Loop n Times

I'm writing a program that finds passwords. I ran into a problem when I saw that the "for" loops to replace parts of the password would have to be repeated for the variable of the chosen password length. The goal of this program is to generate and check a password of any character array, starting with "0" and going through "? (n times)", where '0' is the first character and '?' is the last character.

Is there any way to repeat a for loop a variable number of times without coding them in individually?

Note, based on well-received comments:
The "repeat a for loop" is probably more correctly expressed as "nest several for loops".

int maxLength = 32; //Length of the password, changes via input
char output[maxLength] = "";
for (int currentLength = 1; currentLength < maxLength + 1; currentLength++) {
    for (int characterNumber = 0; characterNumber < 96 /*characters found with switch/case, 95 total*/; characterNumber++) {
        for (int position = currentLength /*position in string*/; position > 0; position--) {
            //For loops of character and position currentLength times
            char newCharacter = '\0'; //Avoiding not initialized error, could be and character
            output[position - 1] = getChar(characterNumber, newCharacter);

Example of an output would be: ...01, 02, 03..., 10, 11..., a0, a1..., ????4afuh7yfzdn_)aj901...

1 answer

  • answered 2018-03-13 20:44 Yunnosch

    You do not need to repeat the for loop. Instead you need to nest it.
    The most inviting solution to implement this is a recursive construct.

    Pseudo code:

    void nestloop(int depth, int width)
            int i;
            for (i=0; i<width; i++)
                nestloop(depth-1, width);
        } else
            /* do whatever you need done inside the innermost loop */