Home > Blockchain >  why does my code in mario more cs50 pset1 print so many hashes for the right pyramid
why does my code in mario more cs50 pset1 print so many hashes for the right pyramid

Time:09-13

[ EDIT: Code has been corrected & output examples added invalidating older comments below. Next time will be better. ]

been trying this cs50 mario more problem for awhile now but i cant seem to find a solution, the right pyramid seems to print out way more than it is supposed to for some reason, my code is below, appreciate any help i can get. thanks

#include <cs50.h>
#include <stdio.h>
int h;
int k;
int j;
int main(void)
{
    while (h<=0 || h>8)
    {
        h = get_int ("input pyramid height:");
    }

    for(j=0; j<h; j  )
    {
        for( k=0; k<=h; k  )
        {
            if (j k<h)
                printf(" ");
            else
                printf("#");
        }
        printf("  ");

        for (int x=0; x<=j; x  )
        {
            for (int y=0; y<=x; y  )
                printf("#");
        }
        printf("\n");
    }
}

this is what im supposed to get for height = 4. (sorry for the lack on info earlier)

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

what i get is this:(

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

CodePudding user response:

Without giving away too much, "examine the problem"...

0th row: print n-0 spaces, the center '#' and LF
1st row: print n-1 spaces, 1x'#', the center again, and 1x'#' (and LF)
2nd row: print n-2 spaces, 2x'#', the center again, and 2x'#'...
3rd row: print n-3 spaces, 3x'#', the center again, and 3x'#'...

Do you see a simple pattern forming here.

Now flip the row numbering vertically:

8th row: print (maybe) 8 spaces, then 1 '#'
7th row: print...
6th row: pr...

Too many variables counting up and down and adding together makes a person's head swim...

Simplify the problem and the pieces should fall into place.

Start fresh. Print a 'pyramid' that is only on one row, then extend that to two rows.

EDIT:

The foregoing was based on my erroneous understanding of the desired output. The "hollow core" of the desired output now makes the title "mario" less random and more significant.

Now that you have posted a 'tidier' version of code, and (with some polishing) the desired/actual output, it is appropriate (on SO) to help with the difficulty you are experiencing...

The 2nd inner for() loop should be the mirror image of the good 1st for() loop. Just count down.

for( k=0; k<=h; k  ) // ascending left
{
    if (j k<h)
        printf(" ");
    else
        printf("#");
}

printf("  ");

for( k=h; k>0; k--) // descending right side
{
    if (j k<h)
        printf(" ");
    else
        printf("#");
}

printf("\n");

This outputs needless spaces, but the code is straightforward becoming "obvious" to the reader.

  • Related