Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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 ;

Saturday, October 17, 2009

C# Hello, World! Console App.

Pretty much every programmer learns "Hello, World!" first. Because C# is so much stronger and surprisingly different from C++ we are starting at the basics in my Advanced Programming class. Here is how you do a Hello, World! console application in C#.

First go into Visual Studio 2008/Express and goto File -> New -> Project. From the template list select "C# Console Application". In the name box go ahead and call the program "HelloWorld". Visual Studio will take it upon itself to generate code that looks something like this:

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

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Now this is a kinda overkill amount of code so we are going to just delete most of it. Remove most of the use lines as well as the namespace. Make sure you delete both the opening and closing curly braces for the name space. If you've done it right it should look like this.

using System;

class Program
{
    static void Main(string[] args)
    {

    }
}

Now we want to rename Program.cs in our file viewer. We want it called the same as our class which in this case is called "HelloWorld". Right Click on Program.cs and select Rename. Type in HelloWorld.cs . Don't forget the .cs which is obviously rather important! When you rename the file it will ask if you want to update references to the file within your code. Click YES.

Now all we have to do is add a console print command to the body of main. To do this type Console.WriteLine("Hello, World") ; into main. The code should now look like this.

using System;

class HelloWorld
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}


With that your program should compile and run. If everything was done right then running it should look like this:


Congrats! Our program works!

- A. R. McGowan.
goodbye, world!

Friday, October 9, 2009

Next Monday

I start classes again. My Classes are as follows:

Advanced Programming: In this class we will take all the stuff we learned in C++ and apply it to C#. While I am glad to have put C++ under my belt there are a ton of annoyances I will not miss about it. Anyone who has ever attempted to perform a switch statement on a series of strings will know exactly what I mean. A man shouldn’t need 12 nested if statements to accomplish one goal unless that goal is to write ugly, hard to follow code.

College Writing I: This is basically English 101. You will most likely not see anything from this class posted on this blog. Hell I don’t even know why I am posting about it here.

Operating Systems: This class is on code portability, I think.

Software Development Life Cycle: I have no clue at all what this class about.



- A. R. McGowan.

next monday is not today

Monday, October 5, 2009

It’s over.

My third term has come to an end. My final project was a hangman game. I have uploaded it in .Zip and .RAR format for anyone who wants to play it. I will gladly post the source code once I get a grade back on it (don’t want less honest people doing bad things). It was an interesting experience trying to make a whole game by myself but it was a fun one. There really is no substitute for trial and error when it comes to coding. No matter how much you read it just can’t compare to sitting down and trying code on your own.

Next term I will be starting C# so I changed the header. Here is hoping it’s as infuriating as C++!
Enjoy the game.

Hangman 1.0 by Austin McGowan .ZIP Format.
Hangman 1.0 by Austin McGowan .RAR Format.


- A. R. McGowan.

this game is racist