October 31, 2018
Consider the code we just studied:
int c;
string message;
int count;
bool res;
Console.WriteLine("Please, enter an integer.");
message = Console.ReadLine();
res = int.TryParse(message, out c);
count = 0; // The user has 3 tries: count will be 0, 1, 2, and then we default.
while (!res && count < 3)
{
count++;
if (count == 3)
{
c = 1;
Console.WriteLine("Using the default value 1.");
}
else
{
Console.WriteLine("The value entered was not an integer.");
Console.WriteLine("Please, enter an integer.");
message = Console.ReadLine();
res = int.TryParse(message, out c);
}
}
Console.WriteLine("The value is: " + c);
Main
method, compile it and execute it.3
, in this case) is stored in a variable instead of being “hard-coded” in the program. Make sure your program works as expected by changing its value to 4, 2, then back to 3.A sample output could be:
do
…while
LoopsRewrite the following code using a do
…while
loop:
Console.WriteLine("Enter an integer between 1 and 10.");
int value = int.Parse(Console.ReadLine());
while (value < 1 || value > 10)
{
Console.WriteLine("Enter an integer between 1 and 10.");
value = int.Parse(Console.ReadLine());
}
Console.WriteLine("The value entered is " + value + ".");
Make sure what you obtained behaves exactly the same way as the code you were given.
do
…while
Loops With Complex Condition!Re-write the code from the first part of this lab (the one that was given, or the version you wrote, that displays the number of attempts taken) as a do
…while
loop. You may want to take the if
statement out of the loop.