#include <cs50.h>
#include <stdio.h>
int main(void)
{
//get height
int h;
do
{
get_int("Height: ");
} while (h < 1 || h > 8);
//
for (int y = 7 - h; y > 0; y--)
{
if (y < 0)
printf("# #");
else
printf(" ");
}
for (int x = 0; h > x; x )
{
printf("#");
}
}
I have been working on this all day and I am just not getting it. sometimes when I check, my code is identical to the lesson yet it won't work. I am not sure if it is my spacing or what. or I'll fix an error and keep working only for it to come back after I had not even touched that area since I got it working. feeling completely lost.
CodePudding user response:
Your code has undefined behavior because h
is uninitialized and you never store the return value of get_int("Height: ")
into it.
The value of h
is undefined, so it can be different for different runs of your program, thus explaining the observed behavior. The fix is easy: just write h = get_int("Height: ");
in the do
/while
loop.
Here is a modified value:
#include <cs50.h>
#include <stdio.h>
int main() {
int h;
do {
h = get_int("Height: ");
} while (h < 1 || h > 8);
for (int y = 7 - h; y > 0; y--) {
if (y < 0)
printf("# #");
else
printf(" ");
}
for (int x = 0; h > x; x ) {
printf("#");
}
return 0;
}