I am very new to coding and learning via Harvard's free CS50 course. Problem set 1 has been difficult, and I think I'm making it more challenging by doing things the hard way, ie I am trying to create functions for my code to get acclimated to how creating functions works. The task is to make a left-aligned pyramid with a height between 1 and 8. I've created functions to get the height from the user and to print the pyramid. The issue is with how the pyramid is printing. It prints correctly, but too many times. So, if the user types '3' when prompted for the height, it should print this:
#
##
###
Instead, it prints that exact pyramid three times:
#
##
###
#
##
###
#
##
###
What would the solution be to fix this based on my below code?
main:
{
int n = get_height();
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n; i++)
{
print_row(n - i - 1, i + 1);
}
}
}
functions:
int get_height(void)
{
int n;
do
{
n = get_int("Height: ");
}
while (n < 1 || n > 8);
return n;
}
void print_row(int spaces, int bricks)
{
// Print spaces
for (int j = 0; j < spaces; j++)
{
printf(" ");
}
// Print bricks
for (int i = 0; i < bricks; i++)
{
printf("#");
}
printf("\n");
}
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n; i++)
{
print_row(n - i - 1, i + 1);
}
}
What the code is doing:
print_row()
prints one single row.n
rows. Or generates one pyramid.n
times. So the outer loop is generating n
pyramids (as the inner loop generates a single pyramid, n * 1 pyramid
is equal to n pyramids
).That's how your code is printing the pyramid n
times. Because after generating the pyramid once, you repeat the process until you've generated n
pyramids.
Simply remove the outer loop.