have trouble programming with multiple loops

Asked 2 years ago, Updated 2 years ago, 30 views

Hello
I'd like to program any number so that the pyramid is tilted 90 degrees to the right in *, but for example, if it's 3, it's output as follows, and if you type 0, it stops.

*
**
***
**
*

I programmed it as follows, but it doesn't work as shown in the attachment.
Where is the mistake?

#include<stdio.h>

int main() {
  inti,j,len,k;
  for(;;){
    scanf("%d", &len);
    if(len==0){break;}
    for(i=1;i<=len;i++){
      for (j=1; j<=i;j++)
        printf("*");
      printf("\n");
    }
    for(k=len-1;k>0;k--){
      for (j=1; j<=len-1;j++)
        printf("*");
      printf("\n");
    }
  }
}

src=

c

2022-09-29 22:27

1 Answers

The loop condition in the comment section below is incorrect. Because j<len-1, you always write * as many as input values -1.I think it's a snake's foot, but the correct answer is j<=k.

#include<stdio.h>

int main() {
  inti,j,len,k;
  for(;;){
    scanf("%d", &len);
    if(len==0){break;}
    for(i=1;i<=len;i++){
      for (j=1; j<=i;j++)
        printf("*");
      printf("\n");
    }
    for(k=len-1;k>0;k--){
      for(j=1;j<=len-1;j++)/*<= Loop condition is j<len-1*/
        printf("*");
      printf("\n");
    }
  }
}


2022-09-29 22:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.