Beginning C# – Formatting output

Real math formulae @iStockphoto / pinobarile Many times when we’re busy churning out code and worrying about the accuracy of our calculations, we can forget that ultimately our users are looking at the results. We have to care about how to present those precious calculations so our users can make sense of it.

And it’s appalling that there are programmers who make up algorithms and write custom functions to get those presentation formats, when the programming language often has a perfectly good in-built function for it. We have to become masters of our chosen programming language! We can start with the following code example.

int numberofapples = 7;
short numberoforanges = 16;
byte red, green, blue;
float distanceinmetres = 42769.307f;
decimal priceofcomputer = 2495.95m;

red = 107;
// the following two lines will fail compilation
// because the values are out of [0, 255] range
//green = -34;
//green = 256;
green = 214;
blue = 0x3f; // this is 63

// this pads the number with zeroes on the left until
// there are 5 digits. If the number is already 5 or
// more digits, then the number is simply printed out.
Console.WriteLine(numberofapples.ToString("d5"));
Console.WriteLine(numberoforanges.ToString("d5"));

// in this case, the number is converted into a string,
// then it's padded on the left with spaces (default) until
// there are 5 characters.
Console.WriteLine(numberofapples.ToString().PadLeft(5));
 // this time, we pad with the letter v (instead of spaces)
Console.WriteLine(numberoforanges.ToString().PadLeft(5, 'v'));

// the maximum number of placeholders is 3: {0}, {1} and {2}
// To go beyond 3, you'll have to use this syntax
//Console.WriteLine("{0}, {1}, {2}, {3}, {4}", new object[] { red, green, blue, 8, 13 });
Console.WriteLine("\\nRGB triplet is [{0}, {1}, {2}]", red, green, blue);
Console.WriteLine("In hexadecimal, they're [{0,0:x2}] [{1,0:x4}] [{2,3:x2}]\\n", red, green, blue);

Console.WriteLine("Distance is {0}", distanceinmetres.ToString("f2"));
distanceinmetres = 42769.304f;
Console.WriteLine("New distance is {0}", distanceinmetres.ToString("f2"));
Console.WriteLine("Distance in scientific notation is {0:e}", distanceinmetres);
Console.WriteLine("Scientific notation (2 dec places) is {0:e2}", distanceinmetres);

Console.WriteLine();

Console.WriteLine("Computer price:\\t{0:N}", priceofcomputer);
Console.WriteLine("Or this way:\\t{0:C}", priceofcomputer);
Console.WriteLine();

DateTime timenow = DateTime.Now;
Console.WriteLine(timenow.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine(timenow.ToString("yyyy-MM-ddTHH:mm:sszzz"));
Console.WriteLine(timenow.ToString("dddd, MM/dd/yyyy"));
Console.WriteLine(timenow.ToString("d MMM yyyy"));
 // for more formats, search MSDN for "Custom DateTime Format Strings"

Console.WriteLine("End of program");
Console.ReadLine();

There’s quite a bit of commenting, so you can follow better while reading the code. It saves a lot of explanation in the post too. There are only a few things I want to point out.

Hexadecimal values
Any integer variable type can be assigned a hexadecimal value instead of plain vanilla numbers. Perhaps the value to be assigned is the result of a binary OR. In this case, hexadecimal values give a clearer idea of how the result is obtained, such as 0xf0 | 0x33 becomes 0xf3.

Hexadecimal values are also used in colour representations, as illustrated in our example code.

Special characters
In the example code, two new characters are introduced: \n and \t. The former is a new line character, and the latter is a tab character. They are also known as escape characters. The backslash \ escapes the normal meaning of the following character. So the “n” is not really printed out.

Automatic rounding
When the float value 42769.307f is printed to 2 decimal places, it’s rounded up to 42769.31. When 42769.304f is printed to 2 decimal places, it’s truncated to 42769.30.

Despite the convenience, I strongly suggest you do not let the computer determine your result. If you want it rounded up, ensure the result yourself.

Thousands separator
Sometimes, when the user deals with numbers in the millions, it’s hard to determine the value of a number such as 43526176849. The user has to count the digit positions to know it’s about 43 billion. This is where using “N” in the format string helps. Commas are used to separate every thousandth digit. Commas are the commonly used separator. If you live in Germany, it’s a period “.”. If you live in Sweden, it’s a space.

The “C” format string is for currency.

Date/Time formats
The combinations for formatting dates and times are the most formidable ones I’ve ever encountered. I am inclined (and due to work requirement) to use the date format used in England, where the day is before the month, like so dd/MM/yyyy.

If you’re working in ASP.NET, I suggest you don’t rely on the culture of the globalisation tag in web.config. There are short cuts for date formatting, such as DateTime.Now.ToString("d") which gives the short date version. I personally find this lacking in descriptive detail. I prefer to manually set the format string. This way, I know what’s gonna come out.

Output
Formatting output screenshot

Homework
Go search MSDN for all the possible format strings, particular those for dates and times. Then play around with the source code. Have fun!

Download source code.

Beginning C# – Arrays and iterations

Numbered mailboxes @iStockphoto / Eliza Snow So you’ve learnt a bit about variables such as ints and floats. What happens if you need, say a bunch of integer variables with similar purposes? For example, ten decimal variables to store prices. This is where arrays come in.

One and two dimensional arraysArrays offer a simple syntax to declare a series of variables of the same type with minimum work. Think of arrays as boxes in sequential order, where the boxes can only hold a certain type of item.

When someone uses the term “array”, the person usually means a one-dimensional array. What’s the difference? Imagine you have a series of boxes. That’s a one-dimensional array. Then imagine each of those boxes is the start of another series of boxes. That’s a two-dimensional array. You can even go on to three-dimensional arrays, where you stack two-dimensional arrays on top of each other.

Alright then, how do you use them? Here comes the source code.

            const int numberofelements = 10;
            double[] multiplesofpi = new double[numberofelements];
            int i;

            for (i = 0; i < numberofelements; ++i)
            {
                // The result of an operation between two numbers has
                // the precision of the number with the higher precision.
                // Math.PI is a double, which has a higher precision than
                // i, an integer. So the result of i * Math.PI is a
                // double.
                multiplesofpi[i] = i * Math.PI;
            }

            // reverse the for loop
            for (i = numberofelements - 1; i >= 0; ----i)
            {
                Console.WriteLine("Box {0} has {1}", i, multiplesofpi[i]);
            }

            Console.WriteLine("End of program");
            Console.ReadLine();

So we declare an array of doubles named multiplesofpi. Note the square brackets after the double. This line

            double[] multiplesofpi = new double[numberofelements];

just tells the compiler that we want an array of doubles. The new keyword simply tells the compiler to create a new array of doubles, with “numberofelements” number of doubles bunched together. Remember the const keyword we learnt?

            for (i = 0; i < numberofelements; ++i)
            {
                // The result of an operation between two numbers has
                // the precision of the number with the higher precision.
                // Math.PI is a double, which has a higher precision than
                // i, an integer. So the result of i * Math.PI is a
                // double.
                multiplesofpi[i] = i * Math.PI;
            }

In the for loop, we assign each element of the array with a value. Each array element can be accessed using an index, which in our case is the variable i.

There are 10 iterations in this case. An iteration refers to an instance of something being done repetitively, such as in a for loop, or while loop. In each iteration, we multiply the number of the iteration by the value of PI, which is about 3.14159. The Math library provided by .NET already contains the constant value of PI, so we’ll just use that.

It takes some getting used to, but computers really like counting from zero. We humans start counting from 1, and for a long time, cannot grasp the idea of nothingness. Computers however, have no problems with zero. Maybe they’re more advanced than us humans…

Anyway, we then practise reversing the for loop with

            // reverse the for loop
            for (i = numberofelements - 1; i >= 0; ----i)
            {
                Console.WriteLine("Box {0} has {1}", i, multiplesofpi[i]);
            }

This is important, because there will come a time in your programming life where going backwards and forwards in a sequential manner is critical. Besides, it trains your mind to think differently, and that’s great by itself.

Homework
Write the first for loop in reverse manner. Then try writing the second for loop in forward manner. Convince yourself that the array will contain the same values, regardless of whether the for loop is in forward manner or reverse manner.

Download the source code.

Programming terms defined – a baker’s dozen

You hungry? I’ve been writing a few tutorials on beginner level programming with C#, and I found it difficult sometimes to explain something without using the actual term. Since you have to know these terms anyway, I might as well give you my brief and possibly unorthodox explanation of the common ones.

  • computer program
  • compiler
  • IDE (integrated development environment)
  • debug
  • programmer
  • source code
  • legacy code
  • DLL (dynamic link library)
  • programming language
  • interpreted language
  • script language
  • procedural programming
  • object oriented programming

computer program
Something that runs in a computer, preferably doing useful work. Also known as software or application.

compiler
A computer program that takes in one or more (text) files and produces one or more computer programs. A classic example of the fractal nature of programming. The output from a compiler can also be a code or class library.

Associated verb: compile.

IDE (integrated development environment)
A computer program with a bunch of nifty abilities including (but not limited to) writing your code, debugging (see below), compiling and even running the output program.

debug
To debug is to find and solve program errors. A program error is also known as a bug. You might have heard of delightful phrases such as squashing bugs, or buggy program (lots of errors).

programmer
A person who writes code and creates computer programs. Also interchangeably used with coder or software developer. As are their verbs, “to program“, “to code” and “to develop“.

source code
Usually used to refer to the (text) files containing the program code, but can also refer to the actual code itself.

legacy code
This refers to source code that’s written in an old(er) computer language. Maintaining legacy code is considered the bane of a programmer’s existence, because there’s nothing new to learn from and there’s very little reference material for it. The source code can be difficult to understand or poorly commented.

DLL (dynamic link library)
Contains a bunch of cool functions, but cannot be run like a program. However, it is used by programs. For example, say you have a DLL containing math functions for calculating means, averages, logarithms and so on. You can then write a program without having to code for those functions. Simply load or link the DLL and you can use those math functions.

programming language
Like human languages, there are many programming languages. Different programming languages just have their own language syntax for writing code.

Note: It’s actually easier to become multilingual in programming languages than in human languages.

interpreted language
The modern programming languages are considered high level languages. This means the language syntax is closer to a human language. It also means the language syntax is harder for a computer to understand. An interpreted language is somewhere in between. Examples are the compiled output (MSIL) from .NET languages (like C#) or Java byte code.

script language
The code from a script language is actually not compiled into anything. Nor does it need to be. A computer program can take in this code, known as a script, and perform actions written in the script.

An excellent example is the scripts used by games. Game engines are usually very complex, written in the high level languages. By their nature, games require lots of flexibility to create lots of options for the player to increase fun. Rewriting game code and recompiling is tedious. Writing game code to read in scripts is easier and allows flexibility, because the scripts can be changed outside of the game code.

Note that there are script languages that are just as complex as a programming language.

procedural programming
This refers to the flow of program logic and/or the style of coding. It is based on procedure calls, where the logic flows from start to end, interrupted only by calling procedures (or functions or methods) and/or control structures like loops and conditions.

Variables can be used by anything for any purpose, because there’s no sense of belonging. The extreme case are the global variables, where any function can access any global variable. The important thing is for the program to continue “flowing”. It is up to the programmer to manage the logic flow.

object oriented programming
Object oriented programming offers the concept of objects. Objects contain variables (or members) and functions (or methods), thus encapsulating logic, making it easier for the programmer to visualise and manage program logic flow.

Beginning C# – Loops and increments

Part of a computer’s charm is its ability to do repetitive tasks in a consistent manner. Doing lightning fast calculations? Good. Doing those calculations with accurate results? Better. Doing those calculations with accurate results everyday for the past year and not complaining? Oh my goodness!

The basis of programming this repetitive behaviour is the loop. There are 4 kinds of loops:

  • for loop
  • while loop
  • do-while loop
  • foreach loop

We’ll look at the for and while loops since they’re more common. In the following example code, we’ll be looking at the calculation of factorials. The factorial of 5, represented in mathematics as 5!, is equal to 1x2x3x4x5 = 120. From Wikipedia’s description of factorials,

In mathematics, the factorial of a non-negative integer n is the product of all positive integers less than or equal to n

Oh yes, the example code:

            const int cnFactorial = 7;
            // the following line of code will fail
            // because cnFactorial is a constant
            //cnFactorial = 5;

            int i, result;

            result = 1;
            for (i = 1; i <= cnFactorial; ++i)
            {
                result = result * i;
            }
            Console.WriteLine("Factorial for {0} is {1}", cnFactorial, result);

            result = 1;
            i = 1;
            while (i < cnFactorial + 1)
            {
                result = result * i;
                i++;
            }
            Console.WriteLine("Result is {1} for {0}!", cnFactorial, result);

            Console.WriteLine("End of program");
            Console.ReadLine();

Constants
Right there on the first line, we hit our new keyword const. It makes our integer variable cnFactorial a constant. Any value first assigned to cnFactorial can never be changed thereafter. Certain values are always the same, like PI (3.14159) or the number of months in a year (12). Adding the const keyword in front of a variable declaration fixes that value, reducing programming errors in case we super coders forget and happen to change an unchangeable value.

The resulting executable is also leaner because the computer compiler will, in effect, replace every occurrence of the constant variable’s name with the constant value. This means that program only has the constant value, and not the constant variable! Constant values take up less space in a program than variables.

Anatomy of a for loop
The for loop has 3 parts, separated by semicolons: initialiser, terminator and incrementor.
for (initialiser; terminator; incrementor)

The initialiser sets the starting conditions for the for loop. This is a good place to code any variable assignments such as resetting variable values.

The terminator is where you code the stopping condition for the for loop. Many a programmer has failed at least once, where they gave the wrong stopping condition and the for loop never ends. At best, the infinite loop keeps printing out messages. At worst, the computer crashes. Code with caution!

The incrementor is where something is usually changed, before checking the terminating condition.

It’s easier to just go through the code:

            result = 1;
            for (i = 1; i <= cnFactorial; ++i)
            {
                result = result * i;
            }

First, we assign the value of 1 to the variable “result”. Then in the initialiser of the for loop, we assign 1 to the variable i. There’s this unofficial type of variable which I’ll call the “loopers”. These looper variables are declared for the sole purpose of running through the for loop. They are also usually single characters by name. i, j, k and a, b, c and p, q, r and x, y, z are the more common ones.

Then the terminating condition reads “If i is less than or equal to cnFactorial, continue”.

The code in the incrementor, ++i, is a shortcut for “Add 1 to the value of i, then assign this new value to i”. It is equivalent to

i = i + 1;

Then the contents of the for loop reads “Multiply the value in variable ‘result’ by the value in variable ‘i’, and then assign this new value to ‘result’.”

The whole flow of the logic is like this:

  1. result has value of 1
  2. Start of for loop, i has value of 1
  3. Check that i (1) is less than or equal to cnFactorial (7), which is true so…
  4. Assign result (1) * i (1) which is 1 (1*1) to result
  5. Do ++i, so i now has value of 2
  6. Check that i (2) is less than or equal to cnFactorial (7), which is true so…
  7. Assign result (1) * i (2) which is 2 (1*2) to result
  8. Do ++i, so i now has value of 3
  9. Check that i (3) is less than or equal to cnFactorial (7), which is true so…
  10. Assign result (2) * i (3) which is 6 (2*3) to result
  11. Do ++i, so i now has value of 4
  12. Check that i (4) is less than or equal to cnFactorial (7), which is true so…
  13. Assign result (6) * i (4) which is 24 (6*4) to result
  14. Do ++i, so i now has value of 5
  15. Check that i (5) is less than or equal to cnFactorial (7), which is true so…
  16. Assign result (24) * i (5) which is 120 (24*5) to result
  17. Do ++i, so i now has value of 6
  18. Check that i (6) is less than or equal to cnFactorial (7), which is true so…
  19. Assign result (120) * i (6) which is 720 (120*6) to result
  20. Do ++i, so i now has value of 7
  21. Check that i (7) is less than or equal to cnFactorial (7), which is true so…
  22. Assign result (720) * i (7) which is 5040 (720*7) to result
  23. Do ++i, so i now has value of 8
  24. Check that i (8) is less than or equal to cnFactorial (7), which is false so we terminate the loop! Whoopee!

The purpose of that incredibly and mind-numbingly long and tedious explanation is so you can appreciate how obliging the computer is when performing repetitive tasks. Anyway, we then print the result. This time, we format the output a little.

            Console.WriteLine("Factorial for {0} is {1}", cnFactorial, result);

The {0} and {1} are placeholders, where {0} refers to the first value (cnFactorial) and {1} refers to the second value (result) after the string.

Why does {0} refer to the first value? Good question. Unfortunately I don’t have an easy answer. It is primarily due to the ancient programming custom of offsets, where the first item is offset by 0 positions. The second item is offset by 1 position. This has caused many beginner programmers to falter.

Homework
Unravel the logic for the while loop in the manner demonstrated above. Yes it’s tedious, but it’ll make you a better person. The while loop takes in only the terminating condition.

You’ll also notice the i++ and it does exactly the same thing as ++i. What’s the difference? Ahhh… but that is your second piece of homework. *grin*

Download source code.

Beginning C# – Precision and control

So you’ve learnt about variables, and you’re wondering, “What’s the practical difference between float, double and decimal variable types?” The difference is in precision.

floats represent single precision real numbers, known as such because of the floating point (or decimal point). doubles represent double precision real numbers, taking up two times the storage space of a float (different from representing two times the range of a float). decimals are a bit special, as they can represent up to 28 significant figures. It’s easier to just show you, so here’s the example code (only contents of the Main function).

            float lowprecision;
            double highprecision;
            decimal exactprecision;
            lowprecision = 1.61803398874989484820f;
            highprecision = 1.61803398874989484820;
            exactprecision = 1.61803398874989484820m;

            Console.WriteLine(lowprecision);
            Console.WriteLine(highprecision);
            Console.WriteLine(exactprecision);

            if (5 > 3)
            {
                Console.WriteLine("First condition");
            }
            else
            {
                Console.WriteLine("Second condition");
            }

            // variables can be declared and assigned a value
            // on the same line of code.
            int truthchecker = 17;
            if (truthchecker == 17)
            {
                Console.WriteLine("The truth is the number 17.");
            }

            if (truthchecker != 17)
            {
                Console.WriteLine("The truth is NOT the number 17.");
            }

            /* The following if-else statement is equivalent to the above
             * two if statements.
             * This comment also illustrates how to use a multiline comment.
             * */
            if (truthchecker == 17)
            {
                Console.WriteLine("2nd check: The truth is the number 17.");
            }
            else
            {
                Console.WriteLine("2nd check: The truth is NOT the number 17.");
            }

            Console.WriteLine("End of program");
            Console.ReadLine();

I’ve used a prominent mathematical number, the golden ratio, as an assigned value for our float, double and decimal variables. You should have noticed the “f” at the end of golden ratio for the float variable assignment, and the “m” for the decimal variable. These are known as suffixes, and there are other suffixes for other variable types. For now, just remember to append an “f” for floats, and an “m” for decimals.

Output for float, double and decimal
When you print the variables, you get 1.618034, 1.61803398874989 and 1.61803398874989484820 respectively. The difference is due to the size of the variable type, affecting how a variable stores a value. So even though the assigned value is the same, the storage and thus the stored value is different for the three variables.

One practical use of preferring floats over the other two types is their speed. Smaller storage sizes translates to faster calculation speeds, while sacrificing accuracy. This is particularly useful in games, such as calculating 3D positional points where the results don’t have to be accurate as much as being quickly computed. The player isn’t going to notice that a box is 0.000005 units off to the left, because he’s too busy shooting some dastardly evil aliens.

When accuracy is extremely important, such as in financial applications, decimals come into play. There are real numbers that floats and doubles cannot represent exactly. For example, the only money values a float or double can represent exactly are 0.00, 0.25, 0.50 and 0.75 (or any dollar amount with those cent values, like 14.75). Why is this? Short answer is it’ll take too long to explain. Try searching with the words “exponent” and “mantissa”. Anyway, with 28 significant figures for accuracy, decimals are ideal for financial applications.

Decisions, choices and forks
Next we learn a new concept: the if statement, one of the most powerful and most used construct for controlling program logic flow.

            if (5 > 3)
            {
                Console.WriteLine("First condition");
            }
            else
            {
                Console.WriteLine("Second condition");
            }

Note where the round brackets () and the curly brackets {} are used.
The above code can be read as “If 5 is greater than 3, then print ‘First condition’, otherwise, print ‘Second condition'”.

The if statement can also be used alone without the else part, such as

            if (truthchecker == 17)
            {
                Console.WriteLine("The truth is the number 17.");
            }

Note: The double equals mean mathematical equality. A single equal mean assignment.
In English, the above code reads “If the variable ‘truthchecker’ is equal to the number 17, print ‘The truth is the number 17.'” Some programmers prefer to reverse the check, like “17 == truthchecker“, to avoid confusing equality checks and assignments. I find it kinda funny to check in reverse, so take your pick.

Then there’s the converse.

            if (truthchecker != 17)
            {
                Console.WriteLine("The truth is NOT the number 17.");
            }

The exclamation mark followed immediately by an equal sign means “not equal to”. So the chunk of code reads “If the variable ‘truthchecker’ is not equal to the number 17, print ‘The truth is NOT the number 17.'”

Multiline commenting
Two consecutive forward slashes // means whatever follows on the same line is a comment, and to be ignored by the computer. What if your comments are too long and go over the next line? You can start another line with // and continue writing comments. Or if you can start your comments with a forward slash and an asterisk /* and end your comments with an asterisk and a forward slash */, which achieves the same effect.

Homework
Wow, that was a long lesson. So homework will be short. Download the source code, and replace the line

if (5 > 3)

with

if ((5 * 4) < (27 - 6))

Change the numbers around and see what happens.

Beginning C# – Variables and operations

So you’re sick with Hello World program code, and want to start doing something. Before you go writing your NASA-approved quantum space engine or the next blockbuster financial application, you have to know about how programs store and manipulate data.

Program data (such as rocket speed or stock prices) are stored in variables, which can be thought of as boxes holding information. We remember information differently from a computer. For example, the information “15” can be a number to us. Or part of an address such as “street 15”. Or 15 dollars. We can pretty much move this data around in our heads.

Here’s the thing: computers need structure. They must know that 15 is a number, and will only store 15 as a number. If 15 is to be part of an address, it must be stored as an address. Moving data from one form to another usually requires telling the computer explicitly to do so, which means you have to write specific code to do that. It’s easier to talk to a computer in its own terms, so we’ll learn about …

Variable types
There are a few variable types, and the most commonly used are those storing numbers and text. There are 2 kinds of number variables; whole numbers and numbers with decimal points (also known as real numbers). In C#, the whole number variables are byte, short and int. The other kind has float, double and decimal. There are more, but these are the common ones.

Why is there a difference? Because computers think, store and manipulate them differently. To the computer, a 7 and a 7.00 are two very different pieces of information. This is very important, especially if you’re doing mathematical calculations.

So we’ll go through them a little bit

  • byte – a whole number between 0 and 255 inclusive
  • short – a whole number between -32768 and 32767 inclusive
  • int – a whole number between -2147483648 and 2147483647 inclusive
  • float – a real number approximately between ±10-45 and ±1038
  • double – a real number approximately between ±10-323 and ±10308
  • decimal – a real number approximately between ±10-28 and ±1028

Why are the real numbers approximations? Again it’s due to the way computers store data. float and double variable types implement the IEEE standard. For now, we’ll simply learn more about these variable types through practical use. Which brings us to the sample code.

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

namespace VariablesAndOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            double anothernumber, yetanothernumber;

            number = 5;
            anothernumber = 3.14159;
            yetanothernumber = 2 * anothernumber;
            
            Console.WriteLine(number);
            Console.WriteLine(anothernumber);
            Console.WriteLine(yetanothernumber);

            number = 3 + 8;
            Console.WriteLine(number);

            // This indicates the end of the program

            Console.WriteLine("End of program");
            Console.ReadLine();
        }
    }
}

A closer look
The first two lines inside the Main function is

int number;
double anothernumber, yetanothernumber;

This is how we declare our variables. In this case, we tell the computer we want a variable of type int and we name it “number”. We also declare two variables of type double, named (unimaginatively) “anothernumber” and “yetanothernumber”. Variables of the same type can be declared on the same line by separating them with a comma.

The next three lines are

number = 5;
anothernumber = 3.14159;
yetanothernumber = 2 * anothernumber;

This is where we assign values to our variables. So we want the integer 5 to be stored in “number”. Then we want 3.14159 to be stored in “anothernumber”. The next line is more interesting. We want two times the value stored in “anothernumber” to be stored in “yetanothernumber”. This means we can assign any appropriate value to a variable, even if the value is stored in another variable.

Manipulating data basically involves mathematical operations (although they are others). They are addition, subtraction, multiplication and division. Their respective operations in code are +, -, * and /.

Commenting
Skipping a couple lines down, we encounter the double forward slash //. This simply tells the computer that whatever follows after the // on the same line is to be ignored, because it’s meant to be read by a human.

Additional note
If you’ve tried running the previous Hello World program straight from the directory by double clicking, you’ll find that it comes up and then disappears. Which is what the following lines will prevent:

Console.WriteLine("End of program");
Console.ReadLine();

By printing “End of program”, you’ll know that the program has indeed reached the end. The Console.ReadLine(); tells the computer to wait for input till the Enter/Return key is hit. This automatically solves the disappearing problem.

Here’s the source code for you to play with.

Homework
Try assigning

number = 1 / 4;
anothernumber = 1.0 / 4.0;

and print out the answer! Can you figure out why the values aren’t what you think they should be?

Beginning C# – Boring Hello World

Programming is about making the computer do what you want. Many programming languages exist, and I’ll concentrate on showing how you can learn C#, one of the easier languages in my opinion.

First, go to the Microsoft Visual Studio C# Express site, and download the free software compiler. A compiler is simply a software that turns your code to a program. The download link should look like this:
Visual Studio C# 2005 Express download

So you install the software and create your first C# project, and name it “ConsoleHelloWorld”. All you need is to add this line of code

Console.WriteLine("Hello World!");

and you’ll have the famous “Hello World” program!

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

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

Compile and run the program in Visual Studio by using Ctrl + F5, or using the menu options [Debug] -> [Start Without Debugging].

The Hello World program is the simplest piece of code with a complete program structure. It is also one of the most boring pieces of code in existence because it does practically next to nothing. That said, the program structure is complete, so we’ll dissect that.

The using statements
These can be thought of as shortcuts for writing code. The following two lines of code are basically the same, thanks to the using System; statement.

Console.WriteLine("Hello World!");
System.Console.WriteLine("Hello World!");

The namespace keyword
It’s just a fence, making sure the code stays in a specific scope. And the meaning of “in scope” is … too much for you to handle at this point.

The class keyword
The “class Program” line of code just means that “Program” is a class, where “Program” is the name of your, uh, class. A class is a chunk of code containing instructions. … And is also too much for you to handle at this point.

The Main thing is …
Where all the action is taking place. It can take other forms besides

static void Main(string[] args)

but I’ll have to explain its other incarnations some other time.

So what can I tell you? Part of your programming experience is to simply ignore what you don’t know and write what code you do know. In our example, you just need to add one line of code. That’s it. Which reminds me. I haven’t explained what that line of code did.

Console is a class, and it has a function called “WriteLine”. If you feed the string “Hello World!” to the function WriteLine, it will be displayed. It’s called a “string” because it’s just a string or a series of characters.

I feel like I’m treating you like a fool, so instead of insulting your intelligence further, I suggest you pick up any C# beginner programmer book. I can almost guarantee the first chapter is on how to write a Hello World program.

And if you don’t get anything yet, then remember that part of being a fantastic programmer is the skill of selective ignorance.

Download source code

Write code that helps write code

Writing tool codeI have discovered a rather surprising fact about my fellow programmer colleagues. Some of them, hate, programming. They go through the day writing code, copying and pasting where appropriate, crushing bugs and then go home. Their distaste for writing code has blinded them to the notion of creating programs to help them in their work. They will only create a program for a project, and not create smaller helper programs to ease the work.

Code generators
For my university thesis, I wrote a simulation program for computer virus behaviour. It was coming along fine, until I wanted to have graphs of my results. The simulation program was written in C and I didn’t know how to create graphs from C. Luckily, I had some experience in Matlab, and remembered how to create graphs for mathematical functions.

So I added some code in my simulation to output the results in a text file, which became the input for my graph generating Matlab code. Basically I used two different programming languages to help in writing my work. The output of one became the input of another.

Random data generation
There was a time when I had to generate a huge amount of data in the database, for a presentation of a web application I developed. And it had to be relatively similar to the real production data. Copying and pasting SQL insert statements wasn’t going to cut it.

So I wrote a small program to generate the insert statements into a SQL script. Then I ran that script in the database. A couple of minutes to run the generation program, and another couple of minutes to run the script, and bingo, mass random data records.

Testbed applications
I have 3 testbed projects, one for console output, one for Windows programs and one for web applications. They are used to test out theories, like what would the output of DateTime.Now.ToString(“dd/MM/yyyy”) look like.

By having these testbeds, I can test my code in a tightly controlled environment, because that testbed application can do only one thing, the code I want to test. Sometimes, testing the code in the actual program is hard, because there can be a lot of other stuff around. Testbeds allow me to just test that chunk of code without all the other distracting fluff. Which helps me write better code.

Custom tool programs
Sometimes, a fully working program is written just so its output can be used in another program. The demoscene and game production are examples of this need.

Demos are computer programs generating stunning visuals and music in real time. Some demo groups, like Conspiracy, have created full-blown applications to help create content such as 3D models and sound files.

Game production teams have tool programs, such as a preview program of texture mapping on a 3D model for artists, or dungeon creation programs to produce the 3D dungeon model used in the game.

These tool programs are not packaged in the final product, yet are essential to the success of the product, because they help make creating the product easier.

Conclusion
Writing code can be easier. Using a professional code generation software might be overkill for a tiny bit of code. Copying and pasting can be tedious. With a little imagination, you can make your programming life easier, by writing code to help you write code.

Texture maps and the soul of programmers

Texture mapping is a technique which adds detail to 3 dimensional models. You’ll see it in graphically rendered movies like Toy Story or Shrek, and in games such as Doom and Final Fantasy XII.

Suppose we have two 3D models, a sphere and a fractal-generated terrain.
3D models of sphere and terrain
When we map a texture (which is just an image) such as
Sunset onto the 3D models, we get
3D models with sunset texture

If we change the texture to
Quiet campus and map that onto the 3D models, we get
3D models with quiet campus texture

Fundamentally, the 3D model is the same. The output changes because the texture is changed. It’s the same with programming. Two programmers will produce two different sets of program code, yet produce the same required logic.

The unique coding fingerprint of the programmer becomes the texture that maps onto the required logic (a 3D model). It’s the way the programmer thinks up a solution. It’s the way the programmer writes and organises code. It’s the personal touch that programmer has imparted onto the resulting program. And a skilled programmer can even alter the logic, such as adding checks not specified in requirements, to create a more useful resulting program.

When you’ve done enough programming of your own, reading other programmers’ code gives you insight into their minds. Understand why a piece of code is written the way it is written. There are many web sites providing programming help with sample code, most of them with further explanation of the code. So read through the entire solution, explanation, code and all.

Yes, you really really just need the code to solve your problem. When you’ve solved your problem, read through the code and try viewing the problem as the original programmer would have. You’ll learn even more because you’ll have gained some fraction of wisdom, and be better at creating solutions. You’ll have developed your unique texture, and the distinctive soul of a programmer.

Fractal nature of computer programming

Have you ever felt like you are doing the same things over and over and over again? Your daily commute, your workday schedule or your programming pattern?

Fractional capacity dimension
MandelbrotFractals possess the distinctive property of self similarity. They look the same when you zoom in and when you zoom out. Take a small part of a fractal, and it looks similar to another part of the fractal.

So how does programming come into the picture?

A simple programming structure
When you write a program, there are typically 3 sections to it:

  • Declare variables
  • Perform logic
  • Obtain a result

In the program, you might write functions to help break up the program into smaller pieces. And in the function code, you

  • Declare variables
  • Perform logic
  • Obtain a result

See any pattern yet? How about programs calling other programs? The caller program declares some variables, calls another program to perform logic, and obtain a result from that callee program.

Self referential
There’s a special type of function whose programming logic involves calling itself again. They are called recursive functions. An example is the function for calculating factorials. The factorial of 6 is the product of all positive integers less than or equal to 6. Or 1*2*3*4*5*6 = 720. The recursive function will be f(n) = n * f(n-1), where f(1) = 1. In code, it looks like

public int Factorial(int x)
{
if (x == 1) return 1;
else return x * Factorial(x - 1);
}

It is programmatically inefficient, but it is concise. (Math is like that sometimes…)

Iterative process of software development
The very cycle of software development is itself self similar. You develop, test, debug, roll out and get feedback from your users. Then based on the feedback, you develop again, test again, debug again, roll out the next version and get more feedback.

Sometimes, it’s even shorter. You write some code for a small part, test it until you’re satisfied with it. Then you write some code for another part and test that until you’re satisfied.

Can you give more programming examples with fractal properties?