How can I print a Pyramid

81 Views Asked by At

I'm trying to make a pyramid equal to the input I get from the user but its not working the way. In the output, the 1st line is blank and from the second line it print a Hash and on second 2 and then 3 and so on... But I want it to start from the 1st line.

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

int main(void)
{
    // Prompt for height
    int n, i, j;
    do
    {
        n = get_int("height: ");
    }
    while (n < 1 || n > 8);
    // For each row
    for (i = 0; i < n; i++) 0 < 5
    {
        // For each column
        for (j = 0; j < i; j++) 
        {
        printf("#");
        }
    printf("\n");
    }
}

If I give it 5 as input, I was expexting this Output

#
##
###
####
#####

But instead, it's giving me this...


#
##
###
####

what's the problem?

1

There are 1 best solutions below

3
Vlad from Moscow On

It seems there is a typo

for (i = 0; i < n; i++) 0 < 5
                        ^^^^^^

If to remove this typo

for (i = 0; i < n; i++) 
{
    // For each column
    for (j = 0; j < i; j++) 
    {
    printf("#");
    }
printf("\n");
}

then the inner loop gets the control for i in the range [0, n-1).

So for example in the first execution of the inner loop there is no its iterations because j = 0 is not less than i = 0.

You need to write it like

    for (j = 0; j < i + 1; j++)