简体   繁体   English

使用for循环创建带有星号的形状

[英]Use of for loops to create shapes with asterisks

I'm studying for a programming test and one of the questions will involve looking at code which prints a shape using asterisks. 我正在学习编程测试,其中一个问题将涉及查看使用星号打印形状的代码。 The code below is similar to what will be on the test, although, the test question will output a different shape. 下面的代码与测试中的代码相似,尽管测试题将输出不同的形状。 I'm at somewhat of a loss as to how this code works. 我对这段代码的工作方式有些茫然。 I understand the concept of a for loop, but not the role each of these for loops plays in the program. 我了解for循环的概念,但不了解每个for循环在程序中所扮演的角色。 Below, is the code and it's output. 下面是代码及其输出。

#include <iostream>
using namespace std;
int main()
{
  int m, n;
  for (m = 0; m<10; m++)
    {
      for (n = 0; n<m; n++) cout << " ";
      for (n = 0; n<(19-2*m); n++) cout << "*";
      for (n = 0; n<m; n++) cout << " ";
      cout << endl;
    }
  return 0;
}

Output: 输出:

*******************
 *****************
  ***************
   *************
    ***********
     *********
      *******
       *****
        ***
         *
for (m = 0; m<10; m++)                      // this one loops over the rows of the shape
{
  for (n = 0; n<m; n++) cout << " ";        // to leave spaces before the shape
  for (n = 0; n<(19-2*m); n++) cout << "*"; // to fill the shape with *
  for (n = 0; n<m; n++) cout << " ";        // to leave spaces after the shape
  cout << endl;                             // change line
}

As the guys stated, the last loop is not required to get this particular shape, but since this is for your test study, make sure to understand that too, since in the test, any similar shape could pop-up, which may require all the loops (otherwise, why the teacher put it there?. 就像大家说的那样,不需要最后一个循环来获得此特定形状,但是由于这是供您进行测试研究的,因此请确保也要理解,因为在测试中,任何类似的形状都可能会弹出,这可能需要所有循环(否则,老师为什么要把它放在那里?。

for (m = 0; m<10; m++) //This is the main loop to print the 10 rows
{
  for (n = 0; n<m; n++) cout << " "; //This loops provide all the spaces before the first element of each row
  for (n = 0; n<(19-2*m); n++) cout << "*"; //prints the *s
  for (n = 0; n<m; n++) cout << " "; //Not required here....you can get the same output without this.
  cout << endl;
}

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

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