0

I'm stuck on an exercise about using printf only to draw a zig-zag pattern in console, the output should be:

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

Here is my code:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int n,i,j;
        printf("Input the height:");
        scanf("%d",&n);
        printf("\n");
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n-i;j++)
                printf(" ");/
            for(j=1;j<=2*i;j++)
            {
                if (j==1||j==2*i-1)
                    printf("*"); 
                else
                    printf (" ");
            }
            printf("\n"); 
            if (i==n) {
                for(j=1; j<=n;j++)
                    printf (" ");
                break ;
            }
        }
    }
}

like this. I'm trying to draw 2 sides of a triangle, but still don't know how to draw.

Tlacenka
  • 520
  • 9
  • 15
ongtypn
  • 35
  • 3

1 Answers1

1

use 2D array as virtual screen

int n,i,j,d;
printf("Input the height:");
scanf("%d",&n);
int width = (n-1)*4+1;
char vscreen[n][width+1];
memset(vscreen, ' ', sizeof vscreen);
for(i=0; i < n; ++i)
    vscreen[i][width] = 0;

for(j=i=0, d=-1; i < width; ++i, j += d){
    vscreen[j][i] = '*';
    if(j == n - 1 || j == 0)
        d = -d;
}
printf("\n");
for(i=n-1;i>=0;--i)
    printf("%s\n", vscreen[i]);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70