i am trying to build a code in which the user should input a number between 1-5. In any other case the program should request the user to input a new number.
My problem is that the program is going to an infinite loop when the user put the wrong input.
I know that there are other ways to fix it(put an "if else" inside" while" but then i have no use for the first line: (int i = get_int("Please enter a number from 1-5\n");.
Any suggestion how to solve the problem using as much of the code below?
int main(void)
{
int i = get_int("Please enter a number from 1-5\n");
while
{
if (i>5 || i<1)
{
printf("You have given the wrong number.Please try again\n");
}
else
{
printf("Your number is %i\n",i);
}
}
}
OK this is the closest i have come
int main(void)
{
blue();
int i;
do
{printf("Please enter a number\n");
scanf("%d", &i);
}
while (i>5 || i<1);
printf("Your number is\033[1;31m %d.\n\n",i);
blue();
printf("Thank you and goodbye\n");
reset();
// return 0;
}
What is missing from the above is that i would like to also print "You have given the wrong number. Please try again" and prompting for an input when the user put something else than 1-5.
OK guys i think i did it but feel free to comment if i can make the codea bit simpler(keep in mind this is my first week to coding).
#include <stdio.h>
#include <cs50.h>
void blue () {printf("\033[1;34m");} // colour blue
void reset () {printf("\033[0m");} //reset colour
void red () {printf("\033[1;31m");} // colour red
void yellow() {printf("\033[1;33m");} // colour yellow
//////////////////////////////////////////////////////////////////////////////////
int main(void)
{
blue();
int i;
printf("Please enter a number\n");
scanf("%d", &i);
do
{
if (i>5 || i<1)
{{printf("Wrong number. Please enter a number\n");
scanf("%d", &i);}
}
}
while (i>5 || i<1);
{
printf("Your number is\033[1;31m %d.\n\n",i);
blue();
printf("Thank you and goodbye\n");
reset();
}
}