简体   繁体   中英

Printing a pattern to the screen in C

I'm in my first programming course ever and have a few questions about an assignment that we've been given.

I'm trying to print the following pattern to the screen:

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

The pattern is supposed to contain 5 rows and each subsequent row has 2 additional asterisks from the row above making roughly a pyramid shape.

I've been working on creating code to do this using for loops (this was part of the instructions) and here's what I have so far:

int main ()
{
    int row;
    int col;

    for (row = 1; row <= 5; row++) //rows
    {
        for (col = 1; col <= row; col++) //columns
        {
            printf_s("*");
        }
        printf_s("\n");
    }
    return 0;
} 

The problem with my code is that I am not accounting for the required empty spaces to get the alignment correct. With the above current code here's what the output looks like:

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

I'm hoping someone can point me in the right direction as to how to re-write my code to get the correct alignment and the correct number of leading spaces.

Thank you in advance.

The outer loop is for each row and the inner loop prints a number of asterisks in the row. YOu have omitted to preceded the row with a suitable number of spaces.

If you change the outer loop to the more conventional:

for (row = 0; row < 5; row++)

It makes the character count arithmetic simpler.

  • The inner loop should be preceded by another loop to print 4 - row spaces.

  • The asterisk loop needs to print row * 2 + 1 asterisks.

You have a loop to print the asterisks but you are not printing out any spaces before that.

And the number of asterisks you print are not correct. For example your output has only 2 * s in second line when there should've been 3.

You could do

printf("%*s", NUM, "");

to print NUM spaces instead of using a separate loop.

Something like

for (row = 0; row < ROWS ; row++) //rows
{
    printf("%*s", ROWS-1-row, "");
    for (col = 0; col < row*2+1; col++) //columns
    {
        printf("*");
    }
    printf("\n");
}

The number of asterisks in each row is one more than double the row number if the row numbering starts from 0 .

ROWS represent the number of rows to be printed.

Try this:
r - count of rows
s - increment
i - rows index
j - columns index
start - starting count of *

#include <stdio.h>

int main(void)
{
    int i,j,r=4,s,start;
    start = 1;
    s = start*2;

    for (i=0;i<r*s;i+=s)
    {
        for (j=0;j<r*s/2-(i/2)-start;j++) printf(" ");
        for (j=0;j<i+start;j++) printf("*");
        printf("\n");
    }

    return 0;
}

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