嵌套“for”循环n次

时间:2018-03-13 20:44:17

标签: c for-loop

我正在编写一个找到密码的程序。当我看到替换部分密码的“for”循环必须为所选密码长度的变量重复时,我遇到了一个问题。该程序的目标是生成并检查任何字符数组的密码,从“0”开始并经过“?(n次)”,其中“0”是第一个字符和“?”是最后一个角色。

有没有办法重复for循环多次而不用单独编码?

请注意,基于广受好评的评论:
“重复一个for循环”可能更准确地表达为“嵌套几个循环”。

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);
        }
    }
}

输出示例如下: ... 01,02,03 ...,10,11 ......,a0,a1 ......,???? 4afuh7yfzdn_)aj901 ...

1 个答案:

答案 0 :(得分:8)

您无需重复for循环。相反,你需要嵌套它 实现它的最有吸引力的解决方案是递归构造。

伪代码:

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 */
    }
}
相关问题