1

My brain is completely stumped. I wrote this out on paper, and I discovered that as the hash tags increase, the spaces decrease going top to bottom. My problem is that the pyramid is left aligned, instead of right. I can't figure it out..

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

//asks and gets input from user.
int main(void){
 printf("What is the height of the pyramids, you desire?");



int height=GetInt();


//fail-safe should the user give a range out of bounds    
 while(height<=0 || height>23){
printf("Invalid number, pleaser enter a valid number. What is the height?");
main();

 }
//constructs the pyramid, based upon the height given by the user.
for(int i=0; i<height; i++)
{
  printf("\n");


for (int k=0;k<=i;k++)
{

 printf(" ");
}
for(int j=0; j<=i;j++){

 printf("#");


}
 }    

}

3 Answers 3

-1

This code is really all over the place. I went and properly indented everything and you can see that the code has a lot of problems. You keep calling main(), which you should never do. You are never checking the input correctly. The problem you are complaining about is because your nested for loops are using the same values. I would rewatch the videos and get an understanding of nesting for loops, using a little math.

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

//asks and gets input from user.
int main(void){
    printf("What is the height of the pyramids, you desire?");



    int height=GetInt();


    //fail-safe should the user give a range out of bounds    
    while(height<=0 || height>23){
        printf("Invalid number, pleaser enter a valid number. What is the height?");
        main();
    }


    //constructs the pyramid, based upon the height given by the user.
    for(int i=0; i<height; i++)
    {
        printf("\n");

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

}
1

https://youtu.be/NAs4FIWkJ4s go to 5:25. It should help. I came here with a very similar problem. It helped me to solve it.

0

#include <cs50.h> #include <stdio.h> void pyramid(int h); int main(void) { int h; do { h = get_int("Height: "); } while (h < 1 || h > 8); pyramid(h); } void pyramid(int hi) { for (int i = 1; i <= hi; i++) { for (int j = hi; j > i; j--) { printf(" "); } for (int k = 1; k <= i; k++) { printf("#"); } printf("\n"); } }

1
  • thank you for your answer it was really helpful :)
    – Meera Hada
    Mar 27, 2023 at 9:10

You must log in to answer this question.

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