CSCI 1301 – Lab 16

Clément Aubert

March 11, 2019

While With Complex Conditions

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);
  1. As always, start by creating a blank project, copy-and-paste that “snippet” into the Main method, compile it and execute it.
  2. Then, copy and, comment it out, and adapt your copy so that the number of attempts (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.
  3. Re-do the previous step, but change the program so that the number of attempts taken so far to enter a correct value will be displayed every time the user enters an incorrect value.
  4. Re-do the previous step, but change the program, so that the number of remaining attempts is displayed.

A sample output could be:

Please, enter an integer (Attempts left: 3).
No!
Please, enter an integer (Attempts left: 2).
-»/«-»*/-*
Please, enter an integer (Attempts left: 1).
Nope.
Using the default value 1.

dowhile Loops

Rewrite the following code using a dowhile 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.

dowhile Loops With Complex Condition! (Optional)

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 dowhile loop. You may want to take the if statement out of the loop.