0

When I run the below program, I get the following output.

Height: 10
#
Height: 15
##
Height: 

/* Copied from

https://www.reddit.com/r/learnprogramming/comments/68hp3e/cs50_mario_c_can_someone_point_me_in_the_right/ */

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

// Function Prototype Declaration
int get_pyramid_height();

int main(void)
{

    for (int height = 1; height < get_pyramid_height(); height++)
    {
        for (int width = 0; width < height; width++)
        {
            printf("#");
        }
        printf("\n");
    }
}

// Function to get user input
int get_pyramid_height()
{
    int height;

    do
    {
        printf("Height: ");
        height = get_int();
    }
    while (height < 0 || height > 23);;

    return height;
}

Could someone please tell me what's wrong with my program?

1

The test condition is evaluated on each iteration, to check whether you should enter the body or end the loop. This includes the whole expression, also your function call.

You could change your loop to for example

for (int row = 1, height = get_pyramid_height(); row < height; row++)

to have it executed only in the initialisation part, and not on each iteration.

You must log in to answer this question.

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