嵌套"for"循环n次

编程入门 行业动态 更新时间:2024-10-24 17:26:39
本文介绍了嵌套"for"循环n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

有没有办法重复for循环可变的次数 而无需分别对其进行编码?

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

注意,基于广为接受的评论: 重复一个for循环"可能更正确地表示为嵌套多个for循环".

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

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

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

推荐答案

您无需重复for循环.相反,您需要将其嵌套. 实现此目的最吸引人的解决方案是递归构造.

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.

伪代码:

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 */ } }

更多推荐

嵌套"for"循环n次

本文发布于:2023-11-30 20:18:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!