---
title: CSCI 1301 -- Lab 21
author: Clément Aubert
lang: en
fontsize: 10pt
documentclass: scrartcl
numbersections: true
links-as-notes: true
papersize: letter
geometry: margin=1in
keywords:
- Computer Science
- Problem solving methods
- Syllabus
- Augusta University
- Bachelor of Science
---


# While With Complex Conditions

Consider the code we just studied:

~~~~~~~{.cs .numberLines .lineAnchors}
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);
~~~~~~~~

#. As always, start by creating a blank project, copy-and-paste that "snippet" into the `Main` method, compile it and execute it.
#. 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.
#.  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.
#. Re-do the previous step, but change the program, so that the number of _remaining attempts_ is displayed.

A sample output could be:

~~~~~~~{.bash}
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.
~~~~~~~


# `do`…`while` Loops

Rewrite the following code using a `do`…`while` loop:

~~~~~~~{.cs .numberLines .lineAnchors}
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.
