简体   繁体   English

嵌套在C ++中的循环三角形

[英]Nested For Loop Triangle in C++

I'm trying to write a nested for loop that prints out this pattern: 我正在尝试编写一个打印出这个模式的嵌套for循环:

x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxx
xxxxx
xxx
x

However, I don't know how to make the coloumn have two more stars than the last one. 但是,我不知道如何让coloumn比最后一颗星还多两颗星。

This is the code I have so far: 这是我到目前为止的代码:

#include <iostream>
using namespace std;

int main()
{
    for(int r = 1; r <= 5; r++)
    {
        for(int c = 1; c <= r; c++)
            cout << "*";
            cout<< endl;
    }
    for(int r1 = 5; r1 >= 1; r1--)
    {
        for(int c1 = 1; c1 <= r1; c1++)
            cout << "*";
            cout<< endl;
    }
    return 0;
}

I'd appreciate it if someone can help me figure this out. 如果有人可以帮我解决这个问题,我会很感激。

What you have now is close, the inner loop termination condition is wrong. 你现在拥有的是接近,内循环终止条件是错误的。 Observe that you need to print 1,3,5,7,9 * s while the row index are 1,2,3,4,5 . 观察到你需要打印1,3,5,7,9 * s,而行索引是1,2,3,4,5 So the number of * to print is: 2*rowIndex -1 . 所以*打印的数量是: 2*rowIndex -1

for(int r = 1; r <= 5; r++){
    for(int c = 1; c <= 2*r -1; c++)
                   //^^^Here is the diff
             cout << "*";
        cout<< endl;
}
for(int r1 = 5; r1 >= 1; r1--){
        for(int c1 = 1; c1 <= 2*r1 -1; c1++)
                        //^^same here
                cout << "*";
        cout<< endl;
}
return 0;

You can see a live demo here: Print Triangle Star pattern 你可以在这里看到现场演示: 打印三角形星形图案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM