Saturday, October 31, 2009

Control Structures

My next assignment is to use control structures. I am going to go ahead and post the code then go back in dissect it for you.

/* Austin McGowan
 Find Largest/Smallest Number Code
 This program finds the largest number with a known amount of numbers
 and it also finds the lowest number with an unknown amount of numbers.
 this project is designed to test knowledge of control structures.*/

using System;


class ControlStructures
{
    static void Main(string[] args)
    {
        bool doExit = false; // Controls near-infinate loop.
        
        while (!doExit)
        {

            int currentNumber = 0 ; // Stores current number.
            int userInput = 0 ; // Store userInput
            int counter = 0 ; // counter for while loops
            int controler = 0 ; // controler for while loops
            string testString ; // For getting strings to int.

            Console.WriteLine("\nWelcome to my Week 2 Application.") ; // say helo.
            Console.WriteLine("[1] Find the largest number with a known quanity of numbers.") ; //Menu Options 1
            Console.WriteLine("[2] Find the smallest number with an unknown quantity of numbers.") ; // Menu options 2
            Console.WriteLine("[3] Quit") ; // menu options 3
            Console.Write("\nPlease enter your input: ") ; // prompt user for input

            testString = Console.ReadLine() ; //read user input to string.
            userInput = int.Parse(testString); //attempt to change string to Int
            Console.WriteLine("userInput = {0}", userInput); // Debug statment

            switch(userInput) //start switch on userinput
            {
                    
                case 1:// put largest number finder here
                    Console.Write("\nHow many numbers would you like to enter?: ") ; //as user how many numbers they have
                    testString = Console.ReadLine() ; //store in string
                    controler =  int.Parse(testString); // change to int

                    while (counter != controler) // start while loop based on the above input
                    {
                        Console.Write("\nInput integer for comparision: ") ; //ask for input
                        testString = Console.ReadLine(); // store in string
                        userInput = int.Parse(testString); // change to int
                        if (userInput > currentNumber) // check to see if user input is greater.
                        {
                            Console.WriteLine("\n{0} is greater than {1}. Setting stored varible to userInput", userInput, currentNumber); // output what is going on
                            currentNumber = userInput; //change current number since users is bigger.
                        }
                        else
                        {
                            Console.WriteLine("\n{0} is less than or equal to {1}. No changed made to stored varibles", userInput, currentNumber); // tell the user what is going
                        }
                        counter++ ; //increase counter so the while loop stops as some point
                    }
                    Console.WriteLine("\nOf the {0} numbers you entered the largest number was {1}.", controler, currentNumber); // out put results to user.
                    break ; // break out of Switch
                case 2: // put lowest number finder here.
                    Console.Write("\nInput integer for comparision (enter -999 to exit): "); // prompt the user for input
                    testString = Console.ReadLine();
                    userInput = int.Parse(testString);
                    currentNumber = userInput;

                    while(userInput != -999) // Make sure the user isn't trying to exit the program
                    {
                        if (userInput < currentNumber) // check if the user's number is lower then the current number.
                        {
                            Console.WriteLine("\n{0} is less than {1}. Setting stored varible to userInput.", userInput, currentNumber); // Tell the user what is going on.
                            currentNumber = userInput; // update the currentNumber variable
                        }
                        else
                        {
                            Console.WriteLine("\n{0} is greater than or equal to {1}. No change made to stored variables." ,userInput, currentNumber); // Tell the user what is going on.
                        }
                        counter++ ; // Increase counter for last output.
                        Console.Write("\nInput integer for comparision (enter -999 to exit): "); // Ask for input
                        testString = Console.ReadLine();
                        userInput = int.Parse(testString);
                    }
                    Console.WriteLine("\nOf the {0} numbers you entered the smallest was {1}.", counter, currentNumber); // Tell the user thier results.
                    break ; //break
                case 3:
                    doExit = true ; // Set to exit the maste while loop
                    Console.WriteLine("Exiting.. \nThanks for coming."); // thank the user.
                    break ;
                default: // invalid input.
                    Console.WriteLine("Invalid Input..") ;
                    break ;
            
            }
        }
    }
}
While I use comments, a lot, that might not be enough for you so I am going to go ahead and break it down some more.

class ControlStructures
{
    static void Main(string[] args)
    {
This is our basic main statment. We are calling the class ControlStructures since that is what we are showing.

bool doExit = false; // Controls near-infinate loop.
        
        while (!doExit)
        {
Here we declare a boolean variable and assign it the value of false. Boolean values can only be true or false. It is important we put this here because it is what gets us into our while loop. In this second we also start into our while loop. This loop will repeat over and over until doExit (our boolean variable) equals true.

int currentNumber = 0 ; // Stores current number.
            int userInput = 0 ; // Store userInput
            int counter = 0 ; // counter for while loops
            int controler = 0 ; // controler for while loops
            string testString ; // For getting strings to int.

These are all out variables. It is good practice to declare variables together and at the top so they are easily located when the time comes to change or update the program. The first four variables are integers and set to zero as thier default value. This is important as everytime the loop runs these variables need to reset to zero. If they aren't it might cause errors in the code. currentNumber will be used to store ethier the highest or lowest number depending on which menu option we are working at that time. userInput will be used to store the integer version of the user's typed number. counter will be used to keep track of loop runs. controler will be used to exit the known value loop. testString is a storage variable to deal with storing userinput. You will see what I mean in a second.

Console.WriteLine("\nWelcome to my Week 2 Application.") ; // say helo.
            Console.WriteLine("[1] Find the largest number with a known quanity of numbers.") ; //Menu Options 1
            Console.WriteLine("[2] Find the smallest number with an unknown quantity of numbers.") ; // Menu options 2
            Console.WriteLine("[3] Quit") ; // menu options 3
            Console.Write("\nPlease enter your input: ") ; // prompt user for input

            testString = Console.ReadLine() ; //read user input to string.
            userInput = int.Parse(testString); //attempt to change string to Int
            Console.WriteLine("userInput = {0}", userInput); // Debug statment
Here is the Console.WriteLine thing we learned last week. This simply displays the menu for the user then askes them for thier input. Once it gets the input it takes it and turns it into a int. This prevents people from inputing inproper numbers and crashing the system. It is the best way to go about it until we learn about exception handleing.

switch(userInput) //start switch on userinput
            {
This starts our switch statment. A switch statement takes a value (in this case userInput) and compares it to multiple cases. If the value matches any of the cases then that case is executed. If the value doesn't match any of the cases then the "defualt" case is executed.

case 1:// put largest number finder here
                    Console.Write("\nHow many numbers would you like to enter?: ") ; //as user how many numbers they have
                    testString = Console.ReadLine() ; //store in string
                    controler =  int.Parse(testString); // change to int

                    while (counter != controler) // start while loop based on the above input
                    {
This is case 1. This will be executed if the user selects 1 from the menu. The second line asks the user for the number of numbers we will be using. It then takes the user input and puts it into controler after converting it to int. After that a while loop is started. This while loop will keep going as long as counter does not equal the new, userinputted value, controler.

Console.Write("\nInput integer for comparision: ") ; //ask for input
                        testString = Console.ReadLine(); // store in string
                        userInput = int.Parse(testString); // change to int
                        if (userInput > currentNumber) // check to see if user input is greater.
                        {
                            Console.WriteLine("\n{0} is greater than {1}. Setting stored varible to userInput", userInput, currentNumber); // output what is going on
                            currentNumber = userInput; //change current number since users is bigger.
                        }
                        else
                        {
                            Console.WriteLine("\n{0} is less than or equal to {1}. No changed made to stored varibles", userInput, currentNumber); // tell the user what is going
                        }
                        counter++ ; //increase counter so the while loop stops as some point
                    }
This is kind of a large amount of code but it all goes back. The first three lines are something you've seen before. We ask for input the take it and change it to an integer and store it in userInput. Now we move into our first if statement. If statements are one of the easist control structures to understand. The above code could be written in english as: If userInput is greater than the currentNumber then tell the user it is great and set currentNumber to equal userInput. If it isn't then tell the user it isn't and do nothing. Line 12 then adds one to the counter variable. counter++ is the same as writing counter = counter + 1. We then close the while loop with }.

Console.WriteLine("\nOf the {0} numbers you entered the largest number was {1}.", controler, currentNumber); // out put results to user.
                    break ; // break out of Switch
These lines will only execute after the user has input all the numbers he wanted to thanks to our while loop. The first line outputs to the user thier largest number and the second line breaks out of the switch statment. "break;" should be included at the end of every case unless you have a special reason for it not to. We we talk about that at a later date.

case 2: // put lowest number finder here.
                    Console.Write("\nInput integer for comparision (enter -999 to exit): "); // prompt the user for input
                    testString = Console.ReadLine();
                    userInput = int.Parse(testString);
                    currentNumber = userInput;
This starts our second case. Since we don't how many numbers they are going to enter we need to provide them with a sentinal value. A sentinal value is a hardcoded value that when reached in some way will exit a loop. In this case we are going to use negative nine hundred ninty-nine. We then take the input and store it in userInput like we have before.

while(userInput != -999) // Make sure the user isn't trying to exit the program
                    {
This line starts our while loop. As you can see we have hardcoded our sentinal value. The user will be prompted to enter number after number until they type -999 which will signal to the program that they are done.

if (userInput < currentNumber) // check if the user's number is lower then the current number.
                        {
                            Console.WriteLine("\n{0} is less than {1}. Setting stored varible to userInput.", userInput, currentNumber); // Tell the user what is going on.
                            currentNumber = userInput; // update the currentNumber variable
                        }
                        else
                        {
                            Console.WriteLine("\n{0} is greater than or equal to {1}. No change made to stored variables." ,userInput, currentNumber); // Tell the user what is going on.
                        }
                        counter++ ; // Increase counter for last output.
                        Console.Write("\nInput integer for comparision (enter -999 to exit): "); // Ask for input
                        testString = Console.ReadLine();
                        userInput = int.Parse(testString);
                    }
Now we start our if statment again. This if statment in english would read as such: If userInput is less than the currentNumber then tell the user and a set currentNumber to the userInput. If it isn't then tell the user and do nothing. Once the if statment completes we increase the counter again. We are going to use this to tell the user how many numbers they put in. Then we ask the user for input again and store it correctly so the while loop can start over again. After that we close the while loop with } .

Console.WriteLine("\nOf the {0} numbers you entered the smallest was {1}.", counter, currentNumber); // Tell the user thier results.
                    break ; //break
These lines just print the results to the user and then break out of the case statment.

case 3:
                    doExit = true ; // Set to exit the maste while loop
                    Console.WriteLine("Exiting.. \nThanks for coming."); // thank the user.
                    break ;
                default: // invalid input.
                    Console.WriteLine("Invalid Input..") ;
                    break ;
            
            } //switch
        } //while
    } // main
} // class
This is the third case. Since the third case exits the program all we have to do is set doExit to true. Remember that from the very begining? This will cause our loop to stop repeating which causes the program to exit. After that we tell the user goodbye and break out of the switch. The next line is the default statment. This will only execute if they didn't enter a valid option when prompted with the menu so we just tell them they did something wrong. The last four lines are us just closing all our statments in order: switch, while, main, class. I hope this makes some sense to some people.

- A. R. McGowan.

break ;

1 comment:

Post a Comment