Carsol Carsol - 3 months ago 21
C Question

Loop loops, yet still having difficulties understanding

I am currently going though the online course CS50. The objective is to create a set of stairs found within the first level of Mario, like the one made from hashtags below. I've gotten to the point of being able to print the height of how high the user entered, yet my loop will not indent any of the hashtags to make the stairs. Any ideas?

What it should look like

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


What it mine looks like

#
#
#
#


The code:

#include <stdio.h>

int main(void)
{
int line = 0;
int blockHeight = blockHeight - 1;
int space = blockHeight - 1;
int hashes = 2;

do
{
printf("please give me a number between the range of 1 and 23:\n");
scanf("%i", &blockHeight);
}

while (blockHeight >= 1 != blockHeight <= 23);
{
printf("thanks for the correct answer!\n");
}

printf("\n\n\n");

for (int i = 0; i < blockHeight; i++)
{
for (int j = 0; j < space; j++)
{
printf(" ");
space--;
break;
}

for (int k = 0; k < hashes; k++)
{
printf("#");
hashes++;
break;
}

for (int z = 0; z < blockHeight; z++)
{
printf("\n");
break;
}

}

}

Answer

1.

int blockHeight = blockHeight - 1;
int space = blockHeight - 1;

This is the wrong way to intialize the variable. change it to

int blockHeight, space;  

After getting the value of blockHeight you can assign space = blockHeight - 1; (after do-while loop)

2.

do
{
    printf("please give me a number between the range of 1 and 23:\n");
    scanf("%i", &blockHeight);
}
while (blockHeight < 1 || blockHeight > 23); // write `||` instead of `!=`
printf("thanks for the correct answer!\n");

it will run do untill the condition is satisfied. After the condition is satisfied it will print the message written after while.
3.

for (int j = 0; j < space; j++)
{
    printf(" ");
    space--;
    break;
}

Change this to

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

because you have written break; in your loop so for loop will work only once and it will exit the loop.

4.

for (int k = 0; k < hashes; k++)
{
    printf("#");
    hashes++;
    break;
}

Change this to

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

As because of break; it will print # once and exit the loop.

5.

for (int z = 0; z < blockHeight; z++)
{
    printf("\n");
    break;
}

No need to write this for loop. Just one line is enough. Change this to

printf("\n");

6.

int main(void)
{
   ////
   // your code
   ////

    return 0; // write this line at the end
}
Comments