---
title: CSCI 1301 -- Lab 28
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
---

# Problem Solving -- A Random Guessing Game

In lab, we developped the following solution to the "random guessing game":

~~~~~~~{.cs .numberLines .lineAnchors}
/*
 * CSCI 1301 -- A Random Guessing Game.
 * 2018/12/04
 * This version (developped during lab) includes multiple
 * enhancements compared to the version developped during class:
 *     1. It uses do ... while loop, factoring some of the code,
 *     2. It performs user-input validation,
 *     3. It counts the number of attempts needed to guess correctly.
 *     (bonus: it gives the maximum possible number to guess).
 */

using System;

class Program
{
    static void Main()
    {
        Random myBot = new Random(); // Creation of a random number generator.
        int myst = myBot.Next(); // Assignment of a random number to "myst". 
        string msg; // (Temporary) variable for the string entered by the user.
        bool validUInput; // Boolean variable to record the "validity" of the string entered.
        int uInput; // Variable for the numerical value entered by the user.
        int attempt = 0; // Counter for the number of attempts.
        
        do // Actual game located inside this loop.
        {
            // User input validation "block" starts.
            do
            {
                Console.WriteLine("Try to guess the mystery number"
                    + $" (enter a number between 0 and {int.MaxValue}).");
                msg = Console.ReadLine();
                validUInput = int.TryParse(msg, out uInput);
            } while (!validUInput || uInput < 0);
            // User input validation "block" ends.

            // Helping the user:
            if (uInput < myst) Console.WriteLine("Too low, try a greater value.");
            else if (uInput > myst) Console.WriteLine("Too high, try a lower value.");

            attempt++; // Incrementing the number of attempts taken.
        } while (uInput != myst);
        Console.WriteLine($"Congrats! You found the mystery number in {attempt} attempts.");

    }
}
~~~~~~~

You can [download this code as a project](RandomGuessGame.zip).


