Home > Blockchain >  How can i print a pyramid using C?
How can i print a pyramid using C?

Time:12-12

I am using C in this case and its my first time creating multiples nested loops.

Let us consider this problem:

    8
   88
  888
 8888
88888
 8888
  888
   88
    8

I wrote this program :

#include <stdio.h>
int main() {
  int n = 9;
  int p = n   1;
  int q = p / 2;
  for (int i = 1; i <= q; i  ) {
    for (int j = i; j <= q; j  ) {
      printf(" ");
    }
    for (int k = 1; k <= i; k  ) {
      printf("8");
    }
    printf("\n");
  }
  for (int o = q   1; o <= n; o  ) {
    for (int l = 1; l <= o; l  ) {
      printf(" ");
    }
    for (int m = o; m <= n; m  ) {
      printf("8");
    }
    printf("\n");
  }
}

Instead of creating a pyramid, it is creating something that looks like this:

     8
    88
   888
  8888
 88888
      8888
       888
        88
         8

What should i do to fix this?

CodePudding user response:

int main() {
  int n = 9;
  int p = n   1;
  int q = p / 2;
  for (int i = 1; i <= q; i  ) {
    for (int j = i; j <= q; j  ) {
      printf(" ");
    }
    for (int k = 1; k <= i; k  ) {
      printf("8");
    }
    printf("\n");
  }
  for (int o = q   1; o <= n; o  ) {
    for (int l = 1; l <= o - q   1; l  ) {
      printf(" ");
    }
    for (int m = o; m <= n; m  ) {
      printf("8");
    }
    printf("\n");
  }
}

https://godbolt.org/z/cPW14b5W1

CodePudding user response:

You're using almost the entire lowercase alphabet as variable names... Who wants to keep track of all of that?

Two variables (one int and one string) suffice...

int main() {
    int i;
    char *out = "     88888";
    i = 1; while( i < 5 ) printf( "%.5s\n", out   0   i   );
    i = 0; while( i < 5 ) printf( "%.5s\n", out   5 - i   );
    return 0;
}
    8
   88
  888
 8888
88888
 8888
  888
   88
    8

Code should be clear & concise. Your readers will thank you...

EDIT
A comment by the OP below the OP suggests that this function should not be limited to 5 characters width.
Once the fundamental (short) code is written, it can be generalised.

int main() {
    int i;
    for( int n = 2; n <= 9; n   ) {
        char *out = malloc( n   n ); // don't need/use '\0'...
        /* Omitting test for failure */
        memset( out   0, ' ', n );
        memset( out   n, n   '0', n );
        i = 1; while( i < n ) printf( "%.*s\n", n, out   0   i   );
        i = 0; while( i < n ) printf( "%.*s\n", n, out   n - i   );
        printf( "=======" ); getchar();
        free( out );
    }
    return 0;
}
  •  Tags:  
  • c
  • Related