Nesting “for” Loop n Times

雨燕双飞 提交于 2020-01-03 18:50:08

问题


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:


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)
{
    if(depth>0)
    {
        int i;
        for (i=0; i<width; i++)
        {
            nestloop(depth-1, width);
        }
    } else
    {
        /* do whatever you need done inside the innermost loop */
    }
}


来源:https://stackoverflow.com/questions/49265552/nesting-for-loop-n-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!