I tried using the Do While loop originally but was having the same results as the while loop. The user must enter a number 28 - 31. Upon the first try if the user would enter the value correctly it would move on to the next part of the code. However, if the user enters an incorrect value it will ask for a number again but, no matter what they enter it keeps repeating.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
printf("Days in month: ");
int daysInMonth = GetInt();
while (daysInMonth < 28 || daysInMonth > 31)
{
printf("Days in month: ");
int daysInMonth = GetInt();
printf("%i\n", daysInMonth);
}
printf("Pennies on the first day: ");
int pennies = GetInt();
while (pennies < 1)
{
printf("Pennies on the first day: ");
int pennies = GetInt();
}
}
The printf statement was for debugging purposes to test if daysInMonth
is reassigning the value.
In the first
while
, you have:This defines a new variable
daysInMonth
, local for thewhile
's body, which hides the outer variable with the same name. So, in the condition of thewhile
loop, you use the outerdaysInMonth
, in the body, you use the innerdaysInMonth
.I guess you want to remove the
int
part from this row and just modify the outerdaysInMonth
.Actually, you have the same situation in the second
while
loop.