D.Dave
D.Dave

Reputation: 77

Simplify for loop without a lot of if-else cases

I should output:

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

And I did output that but my code is too complicated for that kind of exercise:

for (int i = 6; i > 0; i--) {
  if (i == 6) {
    printf("******\n");
  } else {
    if (i == 5) {
      printf("*****\n");
    } else {
      if (i == 4) {
        printf("****\n");
      } else {
        if (i == 3) {
          printf("***\n");
        } else {
          if (i == 2) {
            printf("**\n");
          } else {
            if (i == 1) {
              printf("*\n");
            }
          }
        }
      }
    }
  }
}

As you see there are a lot of if-else cases to look which value i contains and then to decide how many of the symbols per line should be output, but this code is just a massive block of code which, I think, is not necessarily needed. So I came here to ask, how to simplify my code with the same result.

The code should just look a bit more readable. Any idea how to change my code in my case?

Upvotes: 2

Views: 96

Answers (2)

P.W
P.W

Reputation: 26800

If you use another for loop it will be a lot simpler:

for(int i = 6; i > 0;i--) {
    for(int j = 0; j < i; j++) {  
     printf("*");
    }  
    printf("\n");
   }

Upvotes: 3

Blaze
Blaze

Reputation: 16876

You're looking for a nested loop. That's a loop within a loop. To get your desired output, try this:

int main()
{
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6 - i; j++) {
            printf("*");
        }
        printf("\n");
    }
}

Here, the i loop is responsible for the rows (you can see the printf("\n"); that gets run every time) and the j loop is responsible for printing the appropriate amount of "*".

Upvotes: 5

Related Questions