无法掌握嵌套循环的写作技巧

Unable to get hang of writing nested for loops

本文关键字:掌握 嵌套循环      更新时间:2023-10-16

我必须在这个图的中间部分使用嵌套的循环:

+------+  <-- line
|  ^^  |  <-- This is the first line of body
| ^  ^ |  <-- This is the 2nd line of body
|^    ^|  <-- This is the 3rd line of body
+------+ <--  line

对于行,我写道:

void line()
{
int i, width = 6;
cout << "+";
for(i=0; i<width; i++)
{
cout << "-";
}
cout << "+" << endl;
} 

并且它正确输出。但是我找不到嵌套的 for 循环来产生 2 行之间的输出 e

提示:输出 6x6 框的 for 循环如下所示:

for(int i = 1; i <= 6; i++){
for(int j = 1; j <= 6; j++){
cout << "*";
}
cout << endl;
}

因此,下一步是弄清楚使字符在不同的空间中有所不同。下面是向 for 循环添加条件以更改不同空格字符的示例:

#include <iostream>
#include <string>
using namespace std;
int main()
{
int l = 3; 
int r = 4;
for(int i = 1; i <= 6; i++){
for(int j = 1; j <= 6; j++){
if(j == l || j == r)
cout << "^";
else
cout << "*";
}
l -= 1;
r += 1;
cout << endl;
}
}

我希望这有帮助!