c - Wrong output when printing a tent shape with stars -


i'm trying print out hollow, open tent shape using asterisk stars "*". code uses 2 loops, first rows, , other columns.

following code:

void printtent(int n) {        int j = 1;     int = 1;      if (n == 1) {         printf("*");      } else {         for(i = 0; < n; i++) {             for(j = 0; j < n; j++) {                 printf(" ");             }             if(j == n) {                 printf("*");                 for(j = 1; j <= n; j++) {                     printf(" ");                  }             }         }     } }   int main() {     printtent(4); } 

output obtained:

    *        *        *        *     

desired output:

   *   * *  *   * *     * 

i don't think need

if (n == 1) {     printf("*"); } 

we can take care of in you've written in else part.

for n=4, number of spaces printed @ start of each line 3, 2, 1 & 0.

you seem trying accomplish first inner loop. but

for(j = 0; j < n; j++) {     printf(" "); } 

will print n spaces. need reduce number of spaces printed 1 on each iteration of outer loop.

coming second loop,

for(j = 1; j <= n; j++) {     printf(" "); } 

this has similar problem difference being incrementation of number of spaces printed.

try this

void printtentnmmod(int n) {     int j;     int i;      for(i = 0; < n; i++) {         for(j = i; j < n; j++) {             printf(" ");         }         printf("*");         if(i!=0)         {             for(j=0; j<2*(i-1)+1; ++j)             {                 printf(" ");             }             printf("*");         }         printf("\n");      } } 

also, shorten to

void printtent(int n) {     int j;     int i;      for(i = 0; < n; i++) {         printf("%*c", n-i, '*');         if(i!=0)         {             printf("%*c", 2*i, '*');         }         printf("\n");      } } 

the * in %*c set number of places occupied character printed %c.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -