0
#include <cs50.h>
#include <stdio.h>

int main()
{

int height;

do
{

    height = get_int("Enter the height between 1 & 8\n");

}while(height<1 || height>8);


for(int i=0; i<height; i++)
{
    for(int j=height; j>i; j--)
    {
        printf(" ");
    }
   for(int k=0; k<=i; k++)
    {

    printf("#");
    } 

    printf("\n");   
 }
}

Output As you can see on the above output, there is one extra space printed on each hash. You can see on the fourth row of Hash, There is a blank space. How to Correct It?

2 Answers 2

1

You set height equal to four. This also sets j to four.

See how this works on the first line:

i = 0 by definition, so you print a " " every time j is above i and deduct one from j.

You can repeat this four times: j=4, 3, 2 and 1. This is one more than you need. To fix it, you need to change for(int j=height; j>i; j--) for for(int j=height; j>(i+1); j--) or any other equivalent.

0
for(int j=(height-1); j>i; j--)

Fixed It by subtracting -1. However, I am still confused about this Nested For Loop. I think when outer loop executes first, the Inner loop execute everything and then the outer loop executes. isn't that right? Can you please explain how this nested loop works using the above pattern program?

1
  • First computes checks outer loop condition, if true then executes everything within the inner loop and only then executes the outer loop third parameter (i.e. adding one to i). Then it checks again for the new i value and so on.
    – O1G
    Feb 6, 2019 at 15:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .