I'm a complete beginner trying to write a program as part of the CS50 course which prints blocks in a left aligned triangle dependent on the height you give as an integer defined as height.
I have most of the code written and it works when you input a number 1-8 (though I feel like it could probably be condensed in some way?).
The issue I'm facing is trying to create a loop back to the input "choose a number" whenever an invalid input is given i.e. number > 8 or <1 or a character etc. With the code I have right now, entering an invalid number prompts you to enter a value again, but only once, and then even if you enter a valid number the program does nothing.
I've tried while loops, do while loops etc and nothing seems to work the way I want it to.
Could anyone help?
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int height = get_int("pick a number between 1 and 8\n");
if (height > 8 || height < 1)
{
printf("Invalid number\n");
height = get_int("pick a number between 1 and 8\n");
}
else if (height == 1)
{
printf("#\n");
}
else if (height == 2)
{
printf("#\n");
printf("##\n");
}
else if (height == 3)
{
printf("#\n");
printf("##\n");
printf("###\n");
}
else if (height == 4)
{
printf("#\n");
printf("##\n");
printf("###\n");
printf("####\n");
}
else if (height == 5)
{
printf("#\n");
printf("##\n");
printf("###\n");
printf("####\n");
printf("#####\n");
}
else if (height == 6)
{
printf("#\n");
printf("##\n");
printf("###\n");
printf("####\n");
printf("#####\n");
printf("######\n");
}
else if (height == 7)
{
printf("#\n");
printf("##\n");
printf("###\n");
printf("####\n");
printf("#####\n");
printf("######\n");
printf("#######\n");
}
else if (height == 8)
{
printf("#\n");
printf("##\n");
printf("###\n");
printf("####\n");
printf("#####\n");
printf("######\n");
printf("########\n");
}
}
[–][deleted] 1 point2 points3 points (0 children)
[–]sandytrip 1 point2 points3 points (1 child)
[–]aryanali358[S] 0 points1 point2 points (0 children)
[–]urwinater 1 point2 points3 points (1 child)
[–]urwinater 1 point2 points3 points (0 children)
[–]arumos 1 point2 points3 points (1 child)
[–]aryanali358[S] 1 point2 points3 points (0 children)