Tuesday, May 10, 2016

Short Program

Putting Together a Short Program

After learning how to use the functions of C#, a good challenge for yourself is to set a task to complete using the key items of what you know. For myself, I chose to put together a generator to fill in pieces to a bracket for a competition. Because of simplicity, the example I will use is Greek Week, which involves competitions between sororities and fraternities. There will be 5 events, and 5 teams. Three of the events will require a bracket set-up as pictured below:

So there will be one team that gets a bye for the first round of play. In order to deal with this, we will use 2 separate lists. One array will hold the teams to be placed in the brackets, while the other will keep track of what teams have had a bye already. No team shall have more than one bye for the tournament. 

Regarding the final two events which do not require a bracket, they will be performed by teams in random order for time, or judging. This is simple enough, as we will select a random order 1 through 5.

The code for the Bracket of event 1 is shown below:


What happens here is teams are randomly selected into the brackets, and the final team to be picked is placed into the bye list. From this point onward, the team which was assigned the Bye will not be able to get another bracket in which this happens. To account for this, for each event beyond, the teams that cannot get another bye will be removed from the event's list of teams, and placed into the bracket. Thus, each event beyond here will automatically have a team which had a Bye to be in a played game immediately.

The ordered events at the end will contain a very basic structure, and the code is shown below:


This is simple enough, it simply goes through the array until it is exhausted.

Our output will look like this (granted it will be a new outcome each time:


As you can see, building a program in C# is relatively simple, yet efficient. This could easily be expanded to be a much larger scale, for example, possibly a tournament of 15, or 31, or even more. The efficiency of C# as a language enables us to build great programs quickly and relatively painlessly.

Sunday, April 24, 2016

Interesting Capability of C#

While there is an astounding amount of similarity between C# and Java (as mentioned in pretty much every blog post previous to now), today what I would like to show you is an interesting capability of the C# language that is somewhat unique. This capability is output parameters.

Unlike Java where you can only pass parameters into a method, C# has ability to use a method's parameters to obtain output instead of using the return feature. Now this concept may be new to those reading, and I will make this assumption because it is definitely new to me. So I will illustrate this with a simple example from Microsoft's documentation on C# (https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx).


As you can see, when calling the method the variable value is put into Method as a parameter. Method is called and runs, and its output parameter is i which is set to be equal to 44. Thus, value will be assigned the value 44 when the code is executed. 


This capability is rather excellent and can avoid having to return each value that is necessary, since there can be more than one output parameter in a method, just as we can have more than one input parameter. This can allow us to assign variables a specific value from another method easily. 

Also, it is worth noting that C# has a SQL Server capability. Since it is a Microsoft language, this server is available for use whenever it is deemed necessary by a developer. Visual Studio makes this easy to implement, and the use of output parameters make SQL queries easy to pass between methods without much hassle. These are capabilities that may not be needed at all times, but are certainly nice to have in order to complete a task easily.


Thursday, March 17, 2016

Binary Search

Using a binary search within arrays is quite simple with C#. There was some brilliant person on the creation team for this language that decided to provide a method to accomplish this task, all built in to the generic C# commands. This is a built in function that we can call at anytime, just as we can call the "Math." functions.

We will begin our example using a string list array that will be called group which will do as we expect, hold strings. We will use this to store the names of people who are on a group project together. Sometimes people may need to be added or removed, 'tis the way it goes. We will fill the list with values to begin, and immediately sort the list to improve performance:


Now we will write code to search for Jojo. The code to produce this will use group.BinarySearch to find Jojo, and if she is not in the group, then she will be added at the correct location, being in alphabetical order. What this feature does exactly is it looks for the item you list, then we have to test what the return value of it is. If it returns -1, then the item is not within our list. If it returns any number greater than or equal to 0, then we know the item exists in our list already. 

The code to produce this output is shown below:


So, if the index is not found in the list for Jojo, the program will insert her into the array at the location of ~nameOne, which will do the ground work for us and find the correct location. The output is shown below:

As you can see, Jojo has been added at the correct location for her name in alphabetical order.

So using the BinarySearch feature to look for an item within an index is very quick and simple in C# because of the built in functionality of Visual Studio. 

Methods

The path which we have followed with C# being very similar Java definitely continues when it comes to methods, and how we set up programs in general.

To begin, let's start with a blank program. Then we will create a new class outside of our "Program" class and we will call it "Customer". Further, we will create public variables Course and isVegetarian in order to distinguish what types of orders we will be dealing with. The idea here will be to determine how much a customer owes a restaurant for an order that is made. We will keep it simple and give customers two options for Appetizer and Entree, being vegetarian, and non-vegetarian.

In order to figure out what we will need to set our price to, there has to be methods within the Customer class that tell the cooks what to serve, and the cashier how much a customer owes. So we will create two methods in Customer which can be called from our main program class that do these tasks. Code to create this class is shown below:


Note the use of the "this." within the methods. This shows that there must be values being brought into the Customer class to help the program function. So we can see that a non-vegetarian item will cost more in all cases. While entrees are the more expensive than appetizers, as we would assume.

Now this can all be simply placed below our main Program class. There is no need to open up another tab or anything of that sort like we would do in Eclipse. We can do this all from one window, helping us see everything that will be happening once we run the program.

So we have the Customer class variables and methods ready to go. Now we must create instances of this class within our main Program class.

In order to accomplish this task, we will have to use the syntax that we are familiar with of 


Then, we must set the values for the variables in our Customer class in order for the methods to work the way we would expect. A quick way to do this is to initiate these items using this syntax:


Now that these values are set, we can create print statements to tell us the order, and their value:


Note the use of "{int}" and "{0:C}" in the print statements. This is a way of interpreting strings to print. The 0 and 1 will be the location of the course and vegetarian preference, while the 0:C converts the value of the order to dollars.

So we will create a few more instances of the Customer class in Program to produce other menu items, and the output will appear as such below:


Now this is a relatively basic example of how to use methods in C#, but it is more than enough to get you started with creating your own. These can become as simple or as complex as you like, and it provides us with the ability to do much more with our programs more efficiently.

Sunday, February 28, 2016

Loops

There are multiple ways of performing a repeated action, or a loop, in C#. There are four different syntax methods to achieve this:

  1. for
  2. while
  3. do-while
  4. foreach
For loops

The for loop is likely what we are all most familiar with. Using a similar syntax to what we have seen in Java, the construction of a for loop uses a variable, a condition on that variable, and a post-loop action. An example of such is shown below:


This loop is very straight forward, and no different than what we have seen before in Java.


While loops

The while loop is once again familiar. This loop requires that a variable must be declared before entering the loop condition. In other words, we must have initialized a variable to put conditions on before anything happens. An example of a while loop is shown below:


We can see the similarity of this to a for loop, but with the syntax of it being performed in different locations in the code.


Do-While loops

The do-while loop is not much different from a while loop. In this version of a loop, the actions are performed before the conditions are stated. Really, if we take the "while (condition)" from the top, and place it on the bottom of the loop, we have created the do-while. An example is shown below:



Foreach loops

The foreach loop is something that requires no condition, and is best exemplified by performing on an array. What happens here is the code within the loop is performed for each item in the array. The code for this version of a loop is shown below:



So we can see that there are many ways to get the same outputs using loops in C#. There are some methods which are similar to what we have seen before, along with some new ways of achieving results. Personal preferences can be taken into account writing code for loops.

Tuesday, February 16, 2016

Conditionals

The Basics

Now at this point in C#, most of everything we have observed so far is similar to Java, and various other object-oriented languages. So let's dive into conditional statements with C# to see if the same ideas hold true.

The first example I would like so show is a very simple conditional to decide if a declared boolean variable, x is true. This can be done easily by using x.Equals(true) as our condition in the if-then statement to check, as shown below.


Simple. Already we can see that this should be a style that we are familiar with. 

Getting into a more serious subject to check, I would like to show how an if-then-else statement would show me if I would be able to eat or not. We will use another boolean variable, properly named hasFood. We will check to see if hasFood is true, being if it is then I get to eat tonight. If not, I clearly need to go grocery shopping. The code for this weekly scenario is shown below.


Now I realize that this may be too straight forward of an approach to decide if I can eat tonight without going grocery shopping. There must be another variable to add to determine whether I would even have the money to go grocery shopping in the first place. Enter the else-if statement, and the addition of our next boolean variable hasMoney. So if I have food, everything is fine. If I do not have food, the next thing I would need to check is my bank account. Now if this is not empty (or true for our example), then I will be able to go buy groceries. However, if I neither have food or money (or both are false, in this case our else condition), there must be a third option in which I would have to seek desperate measures in order to eat...finding a friend with available guest swipes at the John Carroll Dining Hall. The code to show this situation is below. 


Once again, this is quick and easy to pick up since we have seen code like this before. So now that we are familiar with conditionals in C#, let's check out logical operators other than .Equals().

Logical Operators

The logical operators for C# stick to the same of which we are used to for Java or Python. For example, let a and b be of type int.
  • == b  checks to see if a is equal to b
  • a != b   checks to see if a is not equal to b
  • a > b  checks to see if a is greater than b
  • a < b  checks to see if is greater than b
This is something that we are familiar with, so now that we know how to write conditional statements and use logical operators on variables, a good example to show we know what we are doing is to take a random number x to be from -99 to 99. We can do this by adding a Random function which we will call rand, and its declaration will be the first line of code in our main. Next, since the rand.Next() function only returns a positive value, we will create another int, n, and set it to be a random integer either 0 or 1. If n is 1, we will multiply x by -1, otherwise, we will leave x alone. 

After we have decided the official value of x to check, we will run a multi-conditional statement to determine if x is an EVEN or ODD integer, as well as if x is POSITIVE or NEGATIVE. If x is none of these, then x must be ZERO. The code to implement this is shown below along with one example of its output.


This is all great, right? C# provides us with capabilities and methods of implementation that we are already familiar with to work with conditional statements and logic. Once again, we can see that C# has a lot of overlap with our past knowledge; making the beginning stages of learning the groundwork for the language relatively simple.

Monday, February 8, 2016

Variables, Constants, and Arithmetic

Declaring Variables

Declaring variables in C# is very much similar to how you would do it in Java. For today's post, we will create a new project called Variables.

To begin, let's declare a couple int variables, x and y:


This is easy, right? As you would probably imagine, you can initialize these variables when you declare them (even on the same line), or after declaration, as shown below:


All of these declarations are legal, and can be used by preference for a developer. 

The calculations for these variables shown above, as you would expect, will result in 7 and 10 for x, s, q, and y, t, w respectively. This is straight forward, and we can validate these with our print statement: Console.WriteLine



Different Types of Variables

Now, obviously, int is not the only variable type that you can declare. Using the same syntax, you can declare other variables of the following types : (Source: https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx)

Defining Constants

Constants are declared in a very similar manner, we just have to use some more code to get there. By more code, I really mean one word: const. We define a constant by adding this before a variable declaration to make our value constant, like so:


Once again, easy. Not a whole lot to it as constant declaration is just as quick as variable declaration.

Getting Into It -- Distance Formula

Now this is all nothing all that new to someone with relative experience. So let's dive in!

Let's write a quick program to calculate the distance between two points in a plane. For example purposes, let's calculate the distance between (3,6) and (7,-3). 
  1. We will need to declare 4 int variables named x1, y1, x2, y2, and initialize them to our points.
  2. Then, we will declare a double variable named distance.
  3. To get the value of our distance, we set distance equal to the distance formula. To do this, we will need the help of the Math. functions built in to Visual Studio. We will use Math.Sqrt(number) to obtain a square root, and Math.Pow(number, exponent).
  4. After writing our formula for distance, we will print our value with Console.WriteLine(distance);
    Console.ReadKey();

    IMPORTANT: It is worth noting that the Console.ReadKey(); is necessary to keep our console open to validate we have the correct answer. Without it or Console.ReadLine(); Visual Studio will kill the program upon completion.
  5. The code, and output of our program is shown below:


Quadratic Formula

We will follow the same practices in order to calculate the quadratic formula, to find a value for x. The quadratic formula can be represented by the following equation:
Where the equation is solving for x, we will refer to the following original form to solve for x:


Now to write the code, we will do something similar to our distance formula.
  1. Let a = 2, b = 8, and c = 4.
  2. Let xPlus be equal to the solution of the quadratic formula when we are adding on top, and xMinus for when we are subtracting.We will once again need the assistance of the Math. functions in Visual Studio.
  3. After the calculation, we will print our result. The code, and output is shown below.

This time, we enlist the help of the Math.Round() function to round our answer to 2 decimal places, making the output look cleaner.



So you can see, you can do anything with C# similar to how we have in the past using Java, or Python. It is a matter of declaring the proper variables with the correct methods to obtain what we want. At least that is the case so far into our exploration of C#.

Tuesday, February 2, 2016

Hello World!

Starting C# in Visual Studio

(Click any images throughout to enlarge)

  1. The first step would be to open a Console Application in Microsoft Visual Studio.
    • To do this, Click on File --> New --> Project...
    • Once you have done this, a screen will come up prompting you to select the type of project you wish to open, and giving your project a name.
    • Set up your application by choosing Console Application from the Visual C# menu, select a location to save your project to, and name your project HelloWorld as shown below:

  2. Once you have completed this step, a window named Project.cs will open as shown below:

  3. Now it is time to add our code. We simply will need 3 lines in the Main function to produce our HelloWorld! example. (Note: the semi-colon is used to end a command as in Java)



  4. The "Console.WriteLine" commands will do exactly as they say in the console, they will write lines. The "Console.ReadKey" command will close the program when the user presses any key.
  5. Finally, press the button on the toolbar. and your HelloWorld! program will run. The output is shown below:


After the output is displayed, you can press any key to exit the program, and you are done! You have created your first C# program. At this point, you can save your program, and exit Microsoft Visual Studio.


    Tuesday, January 26, 2016

    Introduction and Resources

    What is C#?
    • "C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java."
      (Source: http://searchwindevelopment.techtarget.com/definition/C)


    C# Compiler


    Why Does C# Exist?
    • C# was created by Microsoft Corporation, with the lead architect being Anders Hejlsberg.
    • "During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system called Simple Managed C (SMC). In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language". Microsoft had considered keeping the name "Cool" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET project was publicly announced at the July 2000 Professional Developers Conference, the language had been renamed C#, and the class libraries and ASP.NET runtime had been ported to C#."
      (Source: https://en.wikipedia.org/wiki/C_Sharp_(programming_language)#History)


    Project Resources
    • One resource that I will be using to learn the language is Microsoft Virtual Academy. The general C# listing of courses can be found here: Microsoft Virtual Academy - C#.
    • Another resource that I may use can be found here, which has a built in compiler to help learn on the same page: http://www.learncs.org/
    • I do not feel that books will be necessary at the time, given the amount of online resources for C#.