Sunday, March 17, 2013

C# Tutorial Series - Part 2: "Hello World"

In this tutorial, (Part 2 of the C# Tutorial Series), we'll be planning, coding, and compiling our first program! The easiest way that I've learned to code over the years is to simply follow a "monkey-see, monkey-do" model of learning, and as such, the "monkey-see, monkey-do" model will be emphasized throughout this entire series of tutorials (and yes, I am calling you a monkey)!

Before we begin coding, there are a few things that we need to go over -- coding practices that will ensure success and reduce debugging time that we'll have to deal with (don't worry about the terminology yet, it'll become easier and easier to understand through context rather than explicitly stating what "debugging" means).

Good Coding Practices:

1) Psuedocode! This is just another way to say "Plan your program out before actually doing the programming." Some people may call "Psuedocode" an "Algorithm," but they are essentially the same thing and are interchangeable.

"Hey Matt, could you take a look at my psuedocode?" is the same thing as "Hey Matt, could you take a look at my algorithm?" -- Later on when we get into some of  the more complicated data structures, we'll use the term "algorithm" to represent a very specific segment of code, but for now, we'll refer to our "planning" step of the coding process as psuedocode.

2) Compile often! One of the biggest mistakes new programmers make is not compiling their programs as often as they should. Programs can get very complicated, and as such, we need to make sure that everything is working as it should be every step of the way.

Don't worry! This may not make sense right now, but by the end of this tutorial, you'll understand what compiling often means and why we do it.

3) Organize & Understand what you're doing! If our code is not organized, then it's hard to understand what we're trying to accomplish. If we don't understand what we're trying to accomplish, then it is pointless to continue coding. It's always a good idea to have a clear view of your goal, and how you plan to achieve that goal as qualitatively and efficiently as possible.


Lets Start Coding!

As I said before, I'll be following the "monkey-see, monkey-do" model. So, with that said, let's jump right in to the code!

1) Start up Visual Studio.
2) In the top left of the menu bar, click FILE>NEW>PROJECT and navigate to Templates>Visual C#>Windows. Click on Console Application and, in type in "Hello World" in the name field. If you'd like, you can also change the location where the program's files will be saved.
This window may look different depending on the version of Visual Studio you are using and/or the theme that you have chosen in Part 1 of the tutorial series.

3) Once you have completed step number 2, you'll be greeted with some default code that looks something like this:

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

namespace Hello_World
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
} 
We don't need a lot of this code yet -- so lets clean it up a bit before we continue coding to reduce confusion (don't worry about the stuff we're deleting, we will cover them in a later tutorial). Delete all of the "using System.______" lines except the first "using System;" line so it looks like this:

using System;

namespace Hello_World
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
} 
Once we've cleaned up the default code a bit, we can begin writing our first Hello World program.

This is actually a very simple program. Either copy & paste these lines of code into your project, or type them out yourself  between the "Main" curly brackets (recommended -- see below) and I'll explain what these lines of code mean afterwards.

using System;

namespace Hello_World
{
    class Program
    {
        static void Main(string[] args)
        {
            //Output "Hello World!" to the console.
            Console.Write("Hello World!");
            //Display the message until the user presses a key or closes the program.
            Console.ReadLine();
        }
    }
}

Before I explain what this does, click the green arrow in the top menu bar to compile and run your program (alternatively, you can press F5 to achieve the same result).

If everything went well, it should look like this:
Congratulations! You just coded, compiled, and executed your first program!
The next step is to understand what you just did, and what these strange lines of code mean.
The psuedocode, or alternatively, the planning portion of this program would be this part of the code:

//Output "Hello World!" to the console.
//Display the message until the user presses a key or closes the program.
As you can see, the psuedocode is a way of visualizing what your program is supposed to do before you begin coding. Below the psuedocode is the actual code that the program uses to preform tasks.

Next, we'll go over what the actual lines of code do:

{
The first thing we should understand is what the brackets in our code is used for. The brackets are used to organize our code in a neat way that is easily readable by human eyes. Any namespace, class, or method (see below) must be organized with these brackets before your program will be able to compile. These brackets are used for controlling the scope of our data, which we will cover in a later tutorial.

;
The second thing we should understand is what the semicolon in our code does. The semicolon is mainly used to tell the program that you have finished typing a line of executable code. The semicolon is not used at the end of methods, namespaces, and class names. It is, however used almost everywhere else (don't worry, if you're missing a semicolon, the compiler will give you an error telling you to fix it; so you'll eventually get the hang of placing your semicolons correctly).

using System;
The using keyword does exactly what it implies. It enables us to use the classes and methods  defined in the .NET Framework's System namespace (or any namespace, for that matter). We will go over this in more depth as we progress through the tutorials, but for now -- the using keyword associated with the System namesapce allows us to use Console.WriteLine and Console.ReadLine methods because they are a part of the System namespace that is included with the .NET Framework. Don't worry too much about this line of code; we will go over this in a lot more depth later in the tutorial series. For now, just make sure that you have "using System;" at the top of every program you write.

namespace Hello_World
The namespace keyword is used simply for organization. Generally, we "name" our namespace with the title of our program; in this case, we have named it "Hello_Word" which is automatically generated when we create a new project file.

For example, we can have a namespace called Shapes. Inside our Shapes namespace, we can have classes and methods for squares, triangles, circles, and so on.

class Program
The class keyword is also a form of organization. The class keyword is used to organize methods.

For example, we can have a class called "Calculator" that has methods for addition, subtraction, multiplication, and division of integer numbers.

The class keyword is used for much more than just organization -- classes are the foundation for objects, which we will study exclusively later on in the tutorial series.

static void Main(string[] args)
Unlike the previous two keywords, this is a little more vague. This line of code is called a method, which uses the keywords static and void to define the method.

A method is a way to organize operations or procedures (lines of code that preform a task) such that we can use it by calling the method's name. In this case, the computer calls the "Main" method when the program is executed, which allows the inner-pieces of the code to run. All programs must have a Main method; otherwise, the program will simply not execute. We can have methods of other names that preform their respective operations as well (this will be explained in more depth as we continue through the tutorial series).

The static keyword allows us to create data types and use methods without first creating an object. Don't worry too much about this yet -- we'll have an entire tutorial series lesson on the static keyword later. Just know that the static keyword allows the Main method to execute without having to be instantiated.

The void keyword allows us to return the Main method without actually returning a value. Programs are made in such a way that everything has a purpose -- whether its' simply to begin, do nothing, and end, or to output an answer for a calculation on a calculator. Due to this nature of programming, all methods must have a return value. The void keyword allows us to return the null statement, which is equivalent to saying "do not return anything." Some other programming languages don't have a void return statement, so they often use 0 as the return to their Main method. *NOTE: Just because we are not returning anything does not mean we are not doing anything. "Return" is simply used to pass around information inside your program to different methods and classes -- in this case, we don't need to pass anything around to another method or class, so we just return null with the void keyword.

Don't worry about the strange "string[] args" in the parenthesis at the end. We will take a closer look at this later.

Console.Write("Hello World!");
Console.ReadLine();
The Console class is a part of the .NET Framework's System namespace, and Write is a method of the Console class. The Console.Write method allows us to output text, integers, and any other information that we want to the console window. The Console.ReadLine method tells the program to wait until it recieves a key-press from the user before exiting (if we do not have this line of code, the program will flash open for a second and then close). There are a few things to note here -- the first being the use of the "dot" in between the class and the method: "Console.Write" or more generally, "Class.Method" -- this is called the member access operator. It allows us to access a member of a namespace, class, or method by prefixing it with a period.

For example, if we want to use the Console class's Write method, we can call it by typing Console.Write("some text") If we want to use the Console class's ReadLine method, we can call it by typing Console.ReadLine(). 

Follow-Up:


1) Define what a namespace is, and what it is used for.

2) Define what a class is, and what it is used for.

3) Define what a method is, and what it is used for.

4) If we had a namespace called Math, with a class called Calculator, with a method called Add(), how would we call the Add method from another program?

5) Define the keyword void, what it does, and why it is used.

6) Code a program that displays "I wrote my first program!" segmented into pieces by each word. When a user presses the Enter key, show the next word.
Your output should look like:
I wrote my first program!

SOLUTIONS


*To download the project files and solutions, click on the link and on the top left, click on FILES>DOWNLOAD.


NEXT LESSON: [Part 3 - "A Simple Calculator"] 

PREVIOUS LESSON: [Visual Studio & The .NET Framework]

2 comments:

  1. The King Casino | Ventureberg
    Discover the rise ventureberg.com/ and fall of the communitykhabar king casino, jancasino one of https://septcasino.com/review/merit-casino/ the world's largest The Casino is operated by novcasino the King Casino Group. You can

    ReplyDelete