I'm doing the CS50 course and I had this exercise in which I have to print a pyramid with # that looks something like this in C language using the height between 1 and 8 (include) chosen by the user:
#
##
###
####
#####
But my code isn't working and I don't want to go to ChatGPT.
I am keen to only get a hint, so I can solve the problem myself.
Here is my code:
int main(void)
{
// Recebe uma altura do usuário entre 1 e 8;
int h;
do
{
h = get_int("Altura: ");
}
while (h < 1 || h > 8);
// acrescenta uma quebra de linha até que atinja a altura
for (int i = 0; i < h; i++)
{
// acrescenta uma # de acordo com a quantidade de quebra de linha
for (int b = 0; b <= i; b++)
{
for (int j = h - 1; j > i; j--)
{
printf(" ");
}
printf("#");
}
printf("\n");
}
}
I did the first pyramid that looks like this:
#
##
###
####
#####
And I know how to do the reverse, because to have the right pyramid I need to replace theses # for blank space, then it'll seems like:
*****
****
***
**
*
So I know I need to make a mix of these two then I can get the right pyramid, but when I mix them, it doesn't work.
****#
***##
**###
*####
#####
Here is the output of my code:
All you need to do is get the int j loop, take out of the b loop and put him inside of the first loop. Also put the initialization as "h - 1".
Here is the code:
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// Recebe uma altura do usuário entre 1 e 8;
int h;
do
{
h = get_int("Altura: ");
}
while (h < 1 || h > 8);
// acrescenta uma quebra de linha até que atinja a altura
for (int i = 0; i <= h; i++)
{
// acrescenta uma # de acordo com a quantidade de quebra de linha
for (int b = 0; b < i; b++)
{
printf("#");
}
printf("\n");
// insere os * de acordo com a quantidade de # em cada linha
for (int j = h - 1; j > i; j--)
{
printf(" ");
}
}
}