简体   繁体   中英

C++ for-loops to display a pattern

So basically I have to make this pattern using for-loops:

*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*

two blank lines

   **********
    *********
     ********
      *******
       ******
        *****
         ****
          ***
           **
            *
Two blank lines
            *
           **
          ***
         ****
        *****
       ******
      *******
     ********
    *********
   ********** 

I'm not too sure if I need to define * as a variable. I know I need to use increments and decrements to make this happen and also need to use the justification to line it up correctly. Some feedback and help would be greatly appreciated. Thanks!

This kind of problem are to teach you how to divide a problem into smaller one to create code that can be reused for multiple patterns.

For example, you could write a function that prints a line

void PrintLine(int length)

And you probably want to specify if you want the line on the left or right

void PrintLine(int length, bool left)

Then all that's left is to make the looping condition that is specific to the shape you are trying to display.

For the first shape:

int one=1;
boolean doit=true;
int counter=0;

while(doit)
{
  printf("\n");
  counter+=one;
  for(int i=0;i<counter;i++)
  {
      printf("*");
  }
  if(counter>maxi)
  {
      printf("\n");
      for(int i=0;i<counter;i++)printf("*");
      one=-one;
  }
  if(counter==0)doit=false;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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