Home

C# Topics: Nesting Conditional Statements

   

Description

A conditional statement or a loop can be included inside of another. This is referred to as nesting. This technique is used to create a condition that directly depends on another. Any statement can be nested inside of another.

To illustrate, we create an appliction used to guess a number. When the application starts, the compiler generates a random number between 1 and 100. Then, the user is asked to guess what that number is. If the user guesses the number the first time, we congratulates him or her. If the user guesses it wrong, the application will ask whether he or she wants to try again. The user must answer with y (or Y) or n (or N). Other answers should be rejected. If the user answers with y or Y, the application prompts again to enter another guess.

Every time the user enters a new guess, the application counts the number of tries. When the user finally guesses the number right, the application will display the number of tries with a congratulating message.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RandomNumberGame3
{
    public class Program
    {
        static void Main(string[] args)
        {
            // This game lets the user guess a number that was
            // randomly generated by the application
            Random RndNumber = new Random();
            // This variable will hold the random number
            int NumberGuessed;
            // This variable will be the number that the user enters
            int NumberEntered = 0;
            // This variable is user to count the number of
            // times the user has guessed
            // To start, set the number of tries to 0
            int NumberOfTries = 0;
            // This variable will hold the user's answer
            // whether to let him or her 
            // continue to guess the number.
            // To start, assume an answer of Q
            string Answer = "q";

            // Generate a random number between 1 and 100
            NumberGuessed = RndNumber.Next(1, 100);

            // Announce the game
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Welcome to the Guess the Number Game");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("= I have a number between 1 and 100 =");

            // This do...while loop lets the user continue guessing the 
            // random number, until the right one is found
            do
            {
                // This application should accept only numbers from 1 to 100
                // This do...while loop keeps prompting the user until a
                // valid number in that range is entered
                do
                {
                    Console.Write("Guess the Number: ");
                    NumberEntered = int.Parse(Console.ReadLine());

                    // If the user enters a number out of that
                    // range, let hime or her know
                    if ((NumberEntered < 1) || (NumberEntered > 100))
                        Console.WriteLine(
			    "You must enter a number between 1 and 100 only.");
                } while ((NumberEntered < 1) || (NumberEntered > 100));

                // Increment the number of tries
                NumberOfTries++;

                // Compare the user's answer to the random number
                // If the user found the right number...
                if (NumberGuessed == NumberEntered)
                {
                    // ... if the user immediately found it
                    if (NumberOfTries == 1)
                    {
                        // ... praise him or her
                        Console.WriteLine(
			    "\nCongratulations! You guessed it on the first try.");
                        Console.WriteLine("You are some type of a genius!!!\n");
                    }
                    else if (NumberOfTries <= 3)
                    {
                        // If the user tried 2 or 3 times, let him or her know
                        Console.WriteLine("\nWonderful! You guessed it on " +
                                          NumberOfTries.ToString() + " tries.");
                        // And congratulate the user
                        Console.WriteLine("You are amazing!\n");
                    }
                    else if ((NumberOfTries > 3) && (NumberOfTries <= 7))
                    {
                        // If the user had to try 4, 5, 6, or 7 times,
			// let him or her know
                        Console.WriteLine("\nGood! You guessed it with " +
                                          NumberOfTries.ToString() + " tries only.");
                        // And encourage the user
                        Console.WriteLine("You really know your way around numbers.\n");
                    }
                    else if (NumberOfTries > 7)
                    {
                        // If the user tried more than 7 times, acknowledge the effort
                        Console.WriteLine("\nYou guessed it after " +
                                          NumberOfTries.ToString() + " tries?");
                        Console.WriteLine(
			    "It looks like you should practice guessing numbers");
                    }

                    return;
                }
                else
                {
                    // Let the user know how high or low his or her guess was
                    if ((NumberGuessed + 10) <= NumberEntered)
                        Console.WriteLine(
			    "The number you entered is w
ay too high :)");
                    else if (NumberGuessed < NumberEntered)
                        Console.WriteLine("Your number is just too high!");
                    else if ((NumberGuessed - 10) >= NumberEntered)
                        Console.WriteLine(
			    "The number you entered is w
ay too low :)");
                    else
                        Console.WriteLine("Your number is just too low!");

                    string Ans = "n";

                    // If the user did not guess the right number, the application asks 
                    // him or if he or she wants to guess again.
                    // This application should accept only y (or Y) or n (or N) answers
                    // This do...while loop prompts the user for
		    // the answer to the question
                    // It keeps prompting the user until he or she has 
                    // entered y (or Y) or n (or N) as the answer
                    do
                    {
                        Console.Write("\nDo you want to try again? (y/n): ");
                        Ans= Console.ReadLine();

                        if ((Ans.ToLower() != "y") && (Ans.ToLower() != "n"))
                            Console.WriteLine(
				"You must enter your answer as y (or Y) or n (or N)");
                    } while ((Ans.ToLower() != "y") && (Ans.ToLower() != "n"));

                    Answer = Ans;
                }

                if (Answer.ToLower() == "n")
                    Console.WriteLine("Good Bye!!!");
            } while (Answer.ToLower() == "y");
        }
    }
}

Home Copyright © 2008 C# Key