Producing a specific pattern

I am trying to produce a specific pattern (shown below) using C programming. I wrote the following code, that does not produce the same output. Would anyone please suggest how I can correct it?

Output should be:

*
* *
* * *
* * * *
* * * *
* * * *
* * * *
* * *
* *
*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <stdio.h>

int main() {

    int row, col;
    
    for (row = 1; row <= 5; row++) {
        for (col = 1; col <= row; col++) {
            printf("* ");
        }
        printf("\n");
    }
    
    for (row = 4; row >= 1; row--) {
        for (col = 1; col <= row; col++) {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}
It looks more like code you "found" rather than code you wrote.

For one thing, it peaks at a height of 5, whereas your requirement stops at 4.

If you had worked your way to that solution iteratively, you would have easily concluded that the solution was another nested for loop to print the central rectangle.

Consider a pattern of the following form.
1
2
3
4
5
6
7
8
9
10
A
A A
A A A
B B B B
B B B B
B B B B
B B B B
C C C
C C
C


A couple of minor tweaks to "your" code...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <stdio.h>

int main() {

    int row, col;
    
    for (row = 1; row <= 3; row++) {
        for (col = 1; col <= row; col++) {
            printf("A ");
        }
        printf("\n");
    }
    
    for (row = 3; row >= 1; row--) {
        for (col = 1; col <= row; col++) {
            printf("C ");
        }
        printf("\n");
    }

    return 0;
}

Gets you this far.

A 
A A 
A A A 
C C C 
C C 
C 


So when you've edited your way to producing a shape containing ABC, you can replace letters with "*" to get your final output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

#define REQCOL 4
#define SYM "* "

void doRow(int numcol) {
	for (int col = 1; col <= numcol; ++col, printf(SYM));
}

int main() {
	for (int row = 1; row <= REQCOL; doRow(row++), printf("\n"));
	for (int row = 1; row <= REQCOL - 2; doRow(REQCOL), row += printf("\n"));
	for (int row = REQCOL; row >= 1; doRow(row--), printf("\n"));
}



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

Last edited on
Many thanks.
Topic archived. No new replies allowed.