Desert Bunker

Writing your first C# program

There are many programming languages in the world of software development that savvy individuals wish to educate their knowledge hungry minds with. Getting your feet wet with some of them can be a daunting task at best. However, C# (pronounced see-sharp) is intended to be clear, understandable, yet cutting-edge and functional with an emphasis in object-oriented practice. It’s for this reason that I believe C# to be one of the languages of choice for the budding programmer.

Let’s jump right in an start off with a simple ‘Hello World’-esque example. We’ll break from the monotonous trend and introduce not just printing a simple text phrase, but also the concept of a ‘loop’. Our goal of this needless program is to print a phrase to your screen and repeat it as many times as you wish, without actually having to repeat the same line of code over and over again to do so.

Copy the following block of code in to your favorite IDE or text editor, compile it, and run it.

using System;
namespace LoopMyText
{
class TextLoop
{
static void Main()
{
int count = 0;
while (count < 20)
{
Console.WriteLine(“1..2..3..BOOM!”);
count++;
}
Console.WriteLine(“Press any key to exit.”);
Console.ReadKey();
}
}
}

In this example I’m sure you’ll notice that the line we write to the console prints itself 20 times, no more, no less. Without getting in to too much detail right now, let’s focus on the function Main().

First, we create an integer using ‘int count = 0;’ (the shorthand ‘int’ representing an Integer in C#) and name it ‘count’. For now, it’s equal to 0. Next, we create the loop by invoking ‘while (count < 20)’. The condition we set within the expression determines whether or not the loop will continue to execute the statement. Our condition translates to: If the value of the Integer named ‘count’ is less than 20, execute all statements within the block surrounded by ‘{ }’. Each time the block of code is run, ‘while’ will check to see if ‘(count < 20)’ is still true.

The first statement we execute ‘Console.WriteLine(“1..2..3..BOOM!”);’ prints text to a Windows console window. We then increment the value of ‘count’ by using the increment operator ‘++’. In other words, each time we loop through our statements, ‘count’ will be equal to a value that is one more than the last time the block of code was executed, thus bringing us closer to making the expression ‘(count < 20)’ untrue. Once this occurs, we escape from the loop and finish the program. If you are having a hard time grasping the idea of how it works, try changing the initial value of ‘count’ from 0 to something else, and see what happens. Conversely, try changing the expression within ‘while’ to a value other than 20 and monitor the effects it has on your result.

Thanks for reading and I hope you enjoyed this crash course.


Categorised as: Programming, Software


Comments are closed.