Nebula learning

Great Nebula @iStockphoto / angelhell The traditional method of teaching involves introducing students to a new concept, then exhaustively explain everything about that concept before moving to the next concept. This is linear learning. I think of it as depth-first learning, where a topic is studied in detail, sometimes to the point of redundancy.

There’s a huge flaw in linear learning. It’s boring. Different learners have different learning styles. When applying one singular teaching method with an emphasis on giving out as much detail as possible, students are interested up to a certain point in the lesson and then stop. They stop because either they’ve learned enough or got bored with the subject. In any case, they need to apply that knowledge and then move on to something else.

Searching for a more comprehensive learning method
Another learning method is spiral learning, where students touch on a new concept, learn to apply it, move on to a related concept, apply that one and move on to another related concept. The idea is for students to gain a level of mastery in other subjects and acquire greater understanding about previously taught subjects. A concept may be revisited again for a deeper discussion, thus completing a cycle or in this case, a spiral.

I think of spiral learning as breadth-first learning, where many related subjects are covered as much as possible. Spiral learning solves the boredom problem in a linear learning pattern. It too has a flaw, though it’s not obvious.

In an academic setting, the topic of study is often determined by the degree requirements, subject prerequisites, a friend’s recommendation or even a whim of the moment. “Related” subjects are weakly connected to each other, where “weak” refers to the level of personal interest. And this is a weak point of spiral learning. Few people know what they want to learn next, so they follow predetermined guides.

They work better for computers
So linear learning and spiral learning, the former being a depth-first, the latter a breadth-first. They follow two standard search methods, the depth-first search and the breadth-first search. Both try to find a sought after item in the shortest amount time or with the least effort. This works well… for a computer program. Computers need structure, a predetermined system to do their work.

I believe human learning behaviour is radically different. Children learn an extraordinary amount of knowledge about many seemingly disparate subjects quickly. They learn to differentiate colours, ride a bike, do math, sing and dance, speak and read and write, be a friend to someone. They learn about as many subjects as they are interested in. Then school kicks in and institutionalised a learning behaviour for every single child.

What happened when we grow up? We are faced with problems to be solved and there’s not enough time and energy to learn linearly. We don’t even do spiral learning. We pinpoint the problem and we search for an exact answer for that problem.

I see this happening particularly in programming forums, where someone post a question and sought an exact answer to that question. A kind soul answered the question and gave an incomplete code sample, which just needed a little tweaking to get it right for the questioner’s unique situation. Keyword here is “unique”. It’s always better for the person to determine if a solution is usable. Not good enough for the questioner though.

If the questioner had the habit of connecting many different concepts at once, a little thought would have given him the answer. The incomplete code sample would simply act as a nudge in the right direction. The habit however, needs to be formed when we’re younger, and generally speaking freer in our time.

The nebula learning pattern
Humans follow a nebula learning pattern. We form interests, emotions and knowledge of different topics and are therefore proficient at different levels. Our knowledge can be visualised as a nebula where denser clouds represent deeper interest and proficiency. We learn about things with no relation to each other, yet sometimes with almost equal amount of interest and intensity. We touch on topics till bored, then jump to another topic.

In a way, our questioner above is following the same pattern. The question posed was important to him, probably because his job depended on it. That’s why he’s interested in the answer. He probably doesn’t even care about the concepts that led to that answer. He just wants to copy and paste the answer.

We don’t all have to become polymaths, but if we can consciously learn and form nebulae of knowledge, I believe the world will be a better place. We have too many specialists anyway.

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.

CSS colours and hexadecimal

CSS, which stands for Cascading Style Sheets, allows you to work design wonders with your HTML. A web page is split into two parts, the design and look versus the data and functions of the page. And CSS is the main driving force behind the former. Aaron’s article gives an excellent introduction to this separation of form and function of a web page. Then stroll through the breathtaking CSS Zen Garden to gain inspiration for your CSS design project.

So why do you need to know anything about hexadecimals? Because a major component of CSS values come from declaring colours. And colours are represented in mainly hexadecimal values.

In CSS, colours are commonly represented as RGB triplets, such as #336699. RGB is a short form of Red, Green and Blue. A discussion of colour theory and representation is beyond the scope of this article. Simply know the six characters (not including the hex sign #) is divided into 3 parts. First two characters represent red, middle two for green and last two for blue.

These two-character parts are the hexadecimal values of the colour component (red or green or blue), and range from 0 to 255. The higher the number, the more of that colour component. So #0000ff represents pure blue. If it’s still new to you, rest easy, because most standard image processing software has a hexadecimal colour converter.

There are other ways of declaring colours in style sheets, such as color:Red. To a non-technical person, that is very useful. But we’re programmers. What if we need to dynamically generate the style sheet?

Learn 5 non-programming stuff

Ok, so you’ve been banging on the keyboards for entire day, spewing out tons of flawless code. Now you’re beat. You swear that if you see any line of code, you’re gonna puke. So I’m going to offer you something different. In fact, five something differents.

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.

Two trains and a bumblebee problem

Bumblebee on flower @iStockPhoto/Eric DelmarI was intrigued by this math problem a while ago. It took me a couple of pages of calculations to get the solution. Then I kicked myself because the solution was actually staring in my face.

I can’t find the original problem now, although there seem to be other variations of it. So I’m going to give you my (highly embellished) version. Then see if you can get the answer. Here goes the story of Blitz the bumblebee and the fateful encounter of two trains…

Blitz the bumblebee and the meeting of two caterpillars
Blitz the bumblebee was an adventurous kind of guy. He’d wander further out in the fields than his fellow bumblebees. Now he’d seen these huge black caterpillars (trains) spewing out lots of grey and black clouds passing his fields before. Now Blitz, despite his big size, could fly very fast. But these caterpillars zoomed past him, leaving him in a whirlwind spiral as he tried to get back into control.

So one sunny morning, he decided to test his limits. He waited for one of these caterpillars, and when he heard their telltale “choo choo” from a distance, he started flying as fast as he could in the direction where the caterpillar would move. When the caterpillar moved close to his level, Blitz simply flew to the head of the caterpillar and hung on.

What a thrill! The wind was howling around him and the scenery was speeding past him. Then Blitz wondered where the caterpillar was going. So, using the caterpillar’s speed as initial momentum, Blitz took off.

To his surprise, he flew even faster than the caterpillar! So Blitz shot straight ahead. After some time, Blitz was starting to worry where he’s going, when he heard the “choo choo” coming from in front of him. Before he realised it, he bounced off another caterpillar. Somehow Blitz survived the bounce and flew, out of instinct, back in the direction where he came from.

This is fun!” Blitz thought. And wondered if he’d meet the first caterpillar again. Sure enough, the first caterpillar appeared, and Blitz bounced off it, and flew towards the second caterpillar. Through this bouncing and flying, it never occurred to Blitz what would happen when the two caterpillars meet.

When the two caterpillars were within sight of each other, Blitz realised that his bounces were getting more frequent. By the time this revelation came, he found he couldn’t stop nor get out of the bouncing cycle anymore.

They’re gonna crash! I’m too young to die!

And Blitz promptly fainted, while the two caterpillars amazingly brushed past each other and continued on their merry way…

The end.

The real math problem
Alright, maybe the original problem wasn’t phrased like that, so I’ll give you the short version.
Two trains and a bumblebee problem diagram
There are two trains running at 45km/h in opposite directions towards each other on two separate (straight) tracks. Assume for the discussion that the difference caused by the separate tracks is negligible. A bumblebee is positioned at the head of the first train. When the trains are 90km apart, the bumblebee flies at 60km/h towards the second train. When the bumblebee meets the second train, it returns and flies back towards the first train. It continues to fly back and forth in this manner until the two trains meet. What is the distance covered by the bumblebee?

I wrote down tons of calculations and numbers. I scrutinised my work and finally found a relationship between the numbers. Then I used mathematical induction to convince myself that the relationship can be written in the form of a geometric progression. The ratio of the geometric progression turned out to be less than 1, so that simplified the equation further. And the answer was … 60km.

Immediately after I got this answer, I found that since the time taken for the two trains to meet is 1 hour (time = distance / speed = 90km / (45km/h + 45km/h)), it also means the bumblebee only flew for 1 hour. With the speed of 60km/h, flying for 1 hour means a distance of 60km covered. I spent about an hour or so and a couple of pieces of paper to figure this out…

Moral of the story? Sometimes, it’s better to think through a problem instead of jumping on the first solution that pops up in your head.

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?