14 C# Tips that improve code efficiency and productivity

C# is a wonderful programming language; I’ve been writing windows apps and working with C# since C# 2.0 and I like it. The C# syntax in general is very straight forward and simple, in addition, I also like the fact that despite the constantly expanding code library, things are still kept readable. Below I have listed 14 tips that you can use to improve code efficiency, make your code more compact and achieve productivity. I have no doubt that you know or use one or more already.

1. Ternary Operator (?:)

I first time read about the ternary operator while I was browsing the list of operators in C# back in 2006, it’s an interesting operator and I still use it today in programming tasks. The ternary operator is very straight forward and simple to understand—I’ll give you a few examples to clear up things and make sure you understand this.

1.1 string IsEligibleToPurchaseAlcohol(int age)
I’ve written a function which prints out a string, based on the age value the user enters. I’ve followed the alcohol laws of the United States, this means that there is a law for alcohol minimum purchase age; you have to be 21 or over to be eligible to buy alcohol. Here’s the code written with If-then-else:

string IsEligibleToPurchaseAlcohol(int age)
{
   string message = null;

   if (age >= 21)
   {
        message = "Congratulations! You are eligible to buy alcohol.";
   }
   else
   {
        message = "Sorry! You're not eligible to buy alcohol.";
   }
   
   return message; 
}

And here is the code written in one single return line using the ternary operator, notice that both functions complete the same check.

string IsEligibleToPurchaseAlcohol(int age)
{
    return age >= 21 ? "Congratulations! You are eligible to buy alcohol." : 
                       "Sorry! You're not eligible to buy alcohol.";
} 

1.2 string PMorAM()
In this second example, I am using the ternary operator to determine if it is PM or AM, and return that in a string with current time + “PM” or “AM”.

string PMorAM()
{
    return string.Format("{0}:{1} {2}", DateTime.Now.Hour, 
         DateTime.Now.Minute, DateTime.Now.Hour >= 12 ? "PM" : "AM"); 
}

1.3 bool Is18(int age)
In this third example, I am using the ternary operator to determine if the user is 18 years old or younger, and return true or false.

bool Is18(int age)
{
    return age == 18 ? true : false; 
}

2. Null-Coalesce Operator (??)

Every time we need to test for null values in our code, the null-coalesce operator (??) becomes handy to use. I’ve created 3 code-snippets below, just to demonstrate code efficiency and to show how much shorter the code can become.

2.1 The regular newbie way of testing for null value

object a = null;
object b = new object();
object c;

if (a != null)
    c = a;
else
    c = b; 

It is very obvious that a C# developer that has just learned to use the ternary operator will rewrite this to a single line.

2.2 Using the ternary operator to test null

object a = null;
object b = new object();
object c = (a != null) ? a : b; 

With the null-coalescing operator we can make this shorter. If the left-hand side equals null, the right-hand side will be assigned, in this context object b.

2.3 Using the null-coalescing operator to test null

object a = null;
object b = new object();
object c = a ?? b;

3. Boolean

The Boolean (a.k.a. bool) is a data type that supports two states, true/false. The bool data type is commonly used to determine whether a return value is true or false, as we saw with the third example in the examples that use the ternary operator. To explain what code efficiency one can gain by just using bool in if-statements and return values, I’ve written some examples below.

3.1 If-else statement
To be more correct, and more efficient one does not need to fix check whether a method will be true or false, only invoke the method name inside the if-statement, and the rest of the check will occur automatically.

if (IndividualsNormalAge() == true)
{
    System.Diagnostics.Debug.Print("Yes!"); 
}
else
{
    System.Diagnostics.Debug.Print("No!"); 
}

To make this more efficient, simply remove == true, and it will be determined autormatically.

if (IndividualsNormalAge())
{
    System.Diagnostics.Debug.Print("Yes!"); 
}
else
{
    System.Diagnostics.Debug.Print("No!"); 
}

3.2 Return
In some cases one does not need to use the ternary operator to return true/false, that’s how simple it is, below I have a few code-snippets:

bool IndividualsNormalAge()
{
    Random r = new Random(); 
    int age = r.Next(1, 113); 
    return (age < 111) ? true : false; 
}

The ? true : false can be removed, and it will still return true/false.

bool IndividualsNormalAge()
{
    Random r = new Random(); 
    int age = r.Next(1, 113); 
    return (age < 111); 
}

It is very easy to understand this, to clarify further, I've added two more code-snippets below:

return (i == 1) ? true : false;

and even shorter:

return (i == 1); // Returns true only if i equals 1

4. Is String Null?

The string.IsNullOrEmpty tests strings by checking for string references that are null, or empty strings. In short, the static method IsNullOrEmpty enables you to simultaneously test whether a String is null or its value is Empty—as tested in the code-snippet below:

if (string.IsNullOrEmpty(s))
    return "This string is null or empty.";
else
    return string.Format("This string is not null or empty, it equals to \"{0}\" ", s);

5. Data Type Conversion

It's very common that we sometimes or very often have to convert data types for various of reasons, for instance, if the we have a decimal variable with a set value, and we want to convert it into an Integer or int an explicit conversion will be performed to achieve this.

int j = 0;
decimal money = 9500.34m;

j = (int)money; // An explicit conversion using cast operator.

The better option is to use the Convert class which supports full Data Type conversion between all data types.

int money = 0; 
string uservalue = null;

uservalue = Console.ReadLine();
money = Convert.ToInt32(uservalue); 

In the first code-snippet we do explicit conversion using a cast operator, and in the second code-snippet we use the Convert class and invoke the ToInt32() method to convert a string to an int. Is there any difference? Yes, of course there's a difference between the first code-snippet and the second code-snippet—I'll explain, explicit conversions strictly requires a cast operator, and that the source and destination variables are compatible. Conversion using a helper class such as Convert allows us to convert between non-compatible types and does not require the use of cast operator, thus, providing a safe conversion method with performance benefits.

6. Using Statement

Allocation of memory is as important as freeing memory. However, in C# we have the Garbage Collector (GC) which takes care of a lot, but some classes in the .NET library implement the IDisposable interface,
and these require manual object disposal. In the code-snippet below, we make a new instance of the SHA1 class, and in the finally code-block we dispose the object.

SHA1 sha1 = SHA1.Create(); 
            
try
{
   StringBuilder sb = new StringBuilder();
   byte[] data = Encoding.UTF8.GetBytes(text);
   byte[] hash = sha1.ComputeHash(data);

   foreach (byte b in hash)
   {
       sb.Append(b.ToString("x2").ToLower());
   }

   hashed = sb.ToString();
}
finally
{
    if (sha1 != null)
        ((IDisposable)sha1).Dispose();
}

A better way is to use the using statement once, as shown below:

// Allocate
using (System.Security.Cryptography.SHA1 sha1 
    = System.Security.Cryptography.SHA1.Create())
{
     //Use the sha1 to computer the hash.
     //sha1 can only be used inside this code-block
}
//Automatically Disposed

In the second code-snippet, using (...) { ... } will only allow the usage of an object once within the curly braces ("{}"), and disposal will happen automatically after the last curly brace. This approach is much better, especially, if we only need to use one class once.

7. Properties

Prior to C# 2.0, programmers used to solve things very differently, see the first code-snippet:

class Child
{
    public Child() { }

    private int age = 0;

    public int GetAge() { return age; }
    public void SetAge(int _age) { age = _age; }
}

In the first code-snippet, a programmer in C# 1.0 was required to write two methods to be able to set and get a value, in this context, the age of a child. However, that's a lot of code, and it quickly gets messy and it's not elegant enough. However, this issue was solved in C# 2.0 with the introduction of Properties. The code-snippet below demonstrates Properties.

class Child
{
    public Child() { }
      
    private int _age = 0;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    } 
}

The Properties are really useful, especially when we need to protect internal variables and not expose them to the outside world. The second code-snippet above clearly protects our internal variable, _age. However, even the second code-snippet isn't elegant enough, what's elegant is the last code-snippet below. Yes, only get; set; —this is an auto-implemented property (called auto-implemented properties) introduced in C# 3.0.

class Child
{
    public Child() { }
    public int Age { get; set; }
}

The last code-snippet is cleaner, safer and more concise since no additional logic is required in the property accessors, in short, more code efficiency benefits.

8. Namespace Alias Qualifier

The Namespace Alias Qualifier (a.k.a. Aliases) in C# lets developers use the alias name instead of the complete namespace. This is very useful, since namespaces in general can become quite long, an alias becomes very handy. In the code-snippet below, Excel is an alias of the Microsoft.Office.Interop.Excel namespace, yeah the default namespace is long, but we've shorten it.

using Excel = Microsoft.Office.Interop.Excel;

...

var excelapp = new Excel.Application();
excelapp.Visible = true;

9. Object Initializers

The old way, to initialize property values from outside of the class, we would have to write either use a constructor or initialize the properties separately as shown in the first code-snippet:

Child child = new Child();
child.Age = 10;
child.Name = "Bryan";
child.StreetAddress = "Seattle, WA 98124";

The code-snippet above, can be written as:

Child child = new Child() { Age = 10, Name = "Bryan", StreetAddress = "Seattle, WA 98124" };

This language feature exists in C# 3.0 and newer versions, but is not supported in C# 1.0 and C# 2.0. In short, this provides a more elegant way to achieve the same thing, in addition, it's a useful shorthand and provides good code productivity.

10. Nullable Types

Every C# developer in the world knows how to work with value types like int, double, bool, char, and so one. They're really useful, but they have one flaw: they simply cannot be set to null, except string which can be set to null. For example, a bool variable can only hold the values true or false, however, putting the question symbol ("?") or as shown below, Nullable it is possible to assign null i.e. undefined.

Nullable<bool> status = null;
int? i = null;

11. Type Inference

C# 3.0 introduces the concept of type inference with the var keyword. The var keyword was added to support anonymous types which is another new feature in C# 3.0. Without this keyword, we would not be able to create a variable of an anonymous type if we always needed to specify the type. The best part is that the compiler determines the type automatically.

string[] Elementaryschools = {"Adams Elementary", "Hyde Elementary School", 
                              "Brookland Elementary", "Meyer Elementary School", 
                              "Thomas Elementary School", "Young Elementary School"};
var school = from name in Elementaryschools
             where name[0] == 'T'
             select name;
foreach (string n in school)
    Console.WriteLine(n);

The output in the console application will be:

Thomas Elementary School

The main reason "Thomas Elementary School" is printed out, is because we say: where name[0] == 'T', we select only the name if it begins with a 'T'. I just wanted to give some code explanation, in case it becomes complicated. The following two declarations of i are functionally equivalent:

int i = 25; //Explicitly typed
var i = 25; //Implicitly typed

12. Lambda Expressions

Lambda expressions were introduced in C# 3.0, and they use the lambda operator =>. Lambda expressions provide a more concise, functional syntax for writing anonymous methods (note: anonymous methods were introduced in C# 2.0). Since functional programming requires a more declarative style of writing code, lambda expressions are handy, in short, lambda expressions are simply functions/methods.

The following code-snippet shows the definition of a delegate and a method that can be used to initialize the delegate:

public delegate int DoubleInteger(int x);

...

class DelegateSample {
    static public int DoubleNow(int x) { return x * 2; }
}

Create and initialize an instance of the delegate, and then call it:

DoubleInteger dint = new DoubleInteger(DelegateSample.DoubleNow); 
Console.WriteLine("{0}", dint(16));

Using lambda expressions, the syntax gets even terser:

DoubleInteger dint = x => x * 2; 
Console.WriteLine("{0}", dint(16));

Lambda expressions provide a powerful shorthand that can be used to significantly speed up C# development. In short, lambda expressions allow C# developers to shorten their code significantly and make it more compact form, isn't this good huh? Of course it is good especially if we want to achieve productivity.

13. Optional and Named Parameters in C# 4.0

C# 4.0 introduces optional and named parameters. Named parameters free us from the need to remember or to look up the order of parameters in the parameter lists of invoked methods. Optional parameters enable us to omit arguments for some parameters. These two language features can be used with Microsoft Office Automation APIs—this is what the second code-snippet demonstrates below.

Word.Application wordapp = new Word.Application() { Visible = true };
object MissingValue = System.Reflection.Missing.Value;
object Filename = @"C:\sampledocument.docx"; 
object ReadOnly = true; 

wordapp.Documents.Open(ref Filename, ref MissingValue, ref ReadOnly, ref MissingValue, 
    ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,ref MissingValue, 
    ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, 
    ref MissingValue, ref MissingValue); 

With the support of optional and named parameters this becomes even shorter:

Word.Application wordapp = new Word.Application() { Visible = true };
wordapp.Documents.Open(@"C:\sampledocument.docx", ReadOnly: true);

The Microsoft.Office.Interop.Word has a method, Documents.Open this method has one required parameter, and 15 optional paramters, that's a lot huh? Thanks to named paramters we're able to omit a few or all the optional paramters by using their names and passing the argument value for each—as already demonstrated in the second code-snippet above, ReadOnly: true.

14. Asynchronous Programming with Async and Await in C# 5.0

Finally, as a bonus I've decided to demonstrate the usage of async and await in C# 5.0. Asynchronous and Synchronous programming has always been useful, especially when we want our application to be able to perform multiple operations at the same time i.e. multitasking. However, the traditional way of writing asynchronous applications is usually complicated, resulting in applications that become difficult to—write, debug, and maintain.

14.1 The traditional way

public delegate int GetValueAsync(int callDuration);

class ProgramA
{
    public ProgramA() { }

    public int GetValueMethod(int callDuration)
    {
        Thread.Sleep(callDuration); 
        int i = ReturnRandomNumber();
        return i; 
    }

    private int ReturnRandomNumber()
    {
        return new Random().Next(1, 1000);
    }
}

C# 5.0 introduces two new keywords, async and await—these help C# developers build asynchronous applications that are capable of achieving multitasking without performance issues.

14.2 The New Modern way

class ProgramB
{
    public ProgramB() { }

    public async void PrintAsync()
    {
        int a = await GetValueAsync(); 
        Console.WriteLine("The Multiplication of one" + 
            " random number with itself is: {0}", a * a);
    }

    private async Task<int> GetValueAsync()
    { 
        int i = ReturnRandomNumber();
        return await Task.FromResult<int>(i); 
    }

    private int ReturnRandomNumber()
    {
        return new Random().Next(1, 1000);
    }
}

Create and initialize one instance of each, and then invoke their methods:

static void Main(string[] args)
{
    ProgramA prgm = new ProgramA();
    GetValueAsync gasync = new GetValueAsync(prgm.GetValueMethod);
    IAsyncResult result = gasync.BeginInvoke(2000, null, null); 
            
    Console.WriteLine("Test method GetValueAsync() from ProgramA begins.");
    Thread.Sleep(300);
    int a = gasync.EndInvoke(result); 
    Console.WriteLine("The Multiplication of one random numbers is: {0}", a * a);
    Console.WriteLine("\n\n");

    ProgramB prgmB = new ProgramB();
    Console.WriteLine("Test method PrintAsync() from ProgramB begins.\n");
    prgmB.PrintAsync();

    Console.WriteLine("\n");
    Console.ReadKey(); 
}

In conclusion, we can easily avoid performance bottlenecks and enhance the overall responsiveness of our C# applications by using asynchronous programming. The new Visual Studio 2012 and .NET Framework 4.5 leverages asynchronous support via a simplified approach, async programming. In Windows 8 the support for asynchronous programming is much more extended thanks to the Windows Runtime (WinRT).

More to Explore

That's a few tips, and I hope you found them helpful. We've now just briefly had a look on 14 different approaches that help C# developers achieve code efficiency, write more compact code, and achieve productivity. However, there is more to explore—for example, in terms code efficiency, using fewer loops to achieve the same result—this is something I did not cover in this article. We'll tackle that next month. In the meantime, explore other methods and approaches that allow you to become a better C# developer, and be sure to drop me an e-mail with suggestions for future articles.
 
Happy coding!
 

C#: Format a String as Currency

As the title of this short article states, this topic is about “Currency formatting”, and I will show some examples on how to do this with C#. When producing a string for output to a customer, it is useful to format any currency value in a more human friendly money format. This is extremely easy in C#.

The standard numeric format specifier I am going to use is the Currency (“C”) Format Specifier, which is formatted like this: {0:C}

decimal price = 9565.50m;
string total = string.Format("{0:C}", price); 
Console.WriteLine(total + "\n\n"); 
Console.ReadKey();

Another way to achieve the same result is by using ToString(),

decimal price = 9565.50m;
Console.WriteLine(price.ToString("C") + "\n\n"); 
Console.ReadKey();

Result:

In addition, one can add more checks, for example, to output the value with a different currency symbol (e.g. $ £ € Lek Kr).

Using CultureInfo.CreateSpecificCulture() one can set the culture information, and thereby adjust to the country and print out the price with the proper money currency symbol.

decimal price = 9565.50m; 
string total = string.Format(CultureInfo.CreateSpecificCulture("en-GB"), "{0:C}", price);
Console.WriteLine(total + "\n\n"); 
Console.ReadKey();  

Result:

To once again show that this works, lets try with the Albanian currency format, “sq-AL”,

string total = string.Format(CultureInfo.CreateSpecificCulture("sq-AL"), "{0:C}", price);

Result:

As I said one can add more checks, I made a method which checks the culturename with a switch statement, and then formats the price string for output:

static string FormatPrice(decimal price, string cultureName)
{
   string formatted = null;
   CultureInfo info = new CultureInfo(cultureName); 
   switch (info.Name)
   { 
       case "en-US":
             formatted = string.Format(CultureInfo.CreateSpecificCulture("en-US"), 
                 "{0:C}", price);
             break; 
       case "en-GB":
             formatted = string.Format(CultureInfo.CreateSpecificCulture("en-GB"), 
                 "{0:C}", price);
             break;
       case "sq-AL":
            formatted = string.Format(CultureInfo.CreateSpecificCulture("sq-AL"), 
                "{0:C}", price);
            break;
       case "se-SE":
            formatted = string.Format(CultureInfo.CreateSpecificCulture("se-SE"), 
                "{0:C}", price);
            break; 
   }

   return formatted; 
}

This method can easily be invoked inside the Console.WriteLine() method,

decimal price = 9565.50m; 
Console.WriteLine(FormatPrice(price, "se-SE") + "\n\n"); 
Console.ReadKey(); 

Result:

Wrapping up

I’m not quite done with this, what’s really missing is real currency conversion support—for example, the ability to convert between American (USD) and European Euro (€) and vice versa. While, this tutorial and its examples are really covered to a level, this means that there’s probably more that can be added.

But for now, happy coding!

C# Detect Windows OS Version

Software developers sometimes have to add additional lines of code to check the Windows Operating System (OS) version numbers. There are a few ways this can be achieved, and I’ll cover them in this tutorial.

There are three traditional methods or ways to do this:

      1. Read information from the Windows Registry, this is very easy; you only have to use the Registry class in .NET.

      2. Use Environment variables. However, it doesn’t give you the additional details you might want. For example: There is no way to detect Windows® 7 editions.

      3. Use the Windows Management Instrumentation (WMI) query, WMI gives you everything you possibly might need in one single shot, and just a few lines of code. However, WMI is not supported in older versions of the Windows® NT Kernel (but this is becoming less of a problem nowadays).

The Code

There’s in fact, a fourth method, which is to use the OSVersion property in .NET found under the Environment class. We will look a this one as well, but first, CPU Architecture. Using the environment variable “PROCESSOR_ARCHITECTURE”.

bool Isx86()
{
   string cpu = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
   return cpu == "x86" ? true : false; 
}

The way we use this code is simple:

if (Isx86())
    Debug.Print("Your CPU architecture is = x86");
else
    Debug.Print("Your CPU architecture is = x64");

However, another method that is more recommended way to check CPU and OS bits is by checking the IntPtr.Size. If IntPtr.Size == 4 it means x86 and if it return IntPtr.Size == 8 it means x64. To save some lines of code, and code a fewer lines, I recommend this.

bool Is64() { return IntPtr.Size == 8 ? true : false; }  

Another solution that is also available, is Environment.Is64BitOperatingSystem, however, this works only in .NET Framework 4.0 and apps made with .NET Framework 4.

Now time to check Windows OS versions. I made a basic class which I named WinOperatingSystem in C#, the code snippet for using is by making a new instance of the class via the constructor.

WinOperatingSystem os = new WinOperatingSystem();  

Usage:

if (os.IsWindows7())
      Debug.Print("Yes this is Windows 7");

if (os.IsWindowsVista() || os.IsWindowsVistaSP2())
      Debug.Print("Yes this is Windows Vista");

if (os.IsWindowsXP() || os.IsWindowsXP64())
      Debug.Print("Yes this is Windows XP"); 

See the image below for the first line of code execution.

Attachment:
File: WinOperatingSystem.cs

For now, happy coding!

XBOX 360 Controller Input with C++ using XInput.h API

The XBOX 360 has become one of the most popular game consoles in the world, for the past years. Game developers nowadays, develop games for both Playstation 3 and XBOX 360. In this short tutorial and articles, I decided to cover the XBOX 360 controller, in addition, also how to implement your own class with C++ and use the XInput.h API.

The XBOX 360 Controller Layout and Buttons

The XBOX 360 Controller layout and buttons (see the image below), the controller has 2x analog sticks, 2x analog triggers, 11x digital buttons and one digital D-Pad.

As any hardware, the XBOX 360 controller has constant hexadecimal values, these are predefined of course.

//
// Constants for gamepad buttons
//
#define XINPUT_GAMEPAD_DPAD_UP          0x0001
#define XINPUT_GAMEPAD_DPAD_DOWN        0x0002
#define XINPUT_GAMEPAD_DPAD_LEFT        0x0004
#define XINPUT_GAMEPAD_DPAD_RIGHT       0x0008
#define XINPUT_GAMEPAD_START            0x0010
#define XINPUT_GAMEPAD_BACK             0x0020
#define XINPUT_GAMEPAD_LEFT_THUMB       0x0040
#define XINPUT_GAMEPAD_RIGHT_THUMB      0x0080
#define XINPUT_GAMEPAD_LEFT_SHOULDER    0x0100
#define XINPUT_GAMEPAD_RIGHT_SHOULDER   0x0200
#define XINPUT_GAMEPAD_A                0x1000
#define XINPUT_GAMEPAD_B                0x2000
#define XINPUT_GAMEPAD_X                0x4000
#define XINPUT_GAMEPAD_Y                0x8000

The constants can be found in Xinput.h (C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\Xinput.h), the Xinput.h is a C/C++ header file with the API code, or function declarations, variables and constant values. By including the Xinput.h in our code we can write custom functions that utilize the API to communicate with the XBOX 360 Wireless Controller. In order for you to be able to use the Xinput.h you’ll have to install Windows SDK 7.1.

Time to write the code

The very first function we will program in Win32 C++ is called: IsXBOXControlConnected(); and this function will be a boolean, this is very obvious and straight forward.

bool IsXBOXControlConnected()
{
   //Invoke the memset(); function to zero the XBOX_CONTROLLER_State. 
   memset(&XBOX_CONTROLLER_State, 0, sizeof(XINPUT_STATE)); 

   //We store the XInputGetState value inside result, note that result is a DWORD which is a typedef unsigned long. 
   DWORD result = XInputGetState(XBOX_CONTROLLER_NUM, &XBOX_CONTROLLER_State); 

   //Check if the controller is disconnected using the Ternary Operator. 
   return  result == ERROR_DEVICE_NOT_CONNECTED ? false : true;  
}

It is easy to verify whether our class and function works, we just make a pointer of the XBOXController* and invoke the constructor with the new keyword to allocate memory and set memory address for it.

#include <Windows.h>
#include "XBOXController.h"
#include <iostream>

using namespace std; 

void main()
{
	XBOXController* xctrl = new XBOXController(0); 
	if(xctrl->IsXBOXControlConnected())
	      cout << "The XBOX 360 controller is connected!" << endl; 
	else 
	      cout << "The XBOX 360 controller is disconnected!\nPlease check your XBOX 360 controller again!" << endl; 

	cin.get(); 
}

When we execute the above code in main.cpp we either see “The XBOX 360 Controller is connected!” or “The XBOX 360 controller is disconnected! Please check your controller again!”, see the command screenshot below:

Awesome, let’s move onto the Vibration(); function. According to the MSDN Documentation, the vibration accepts values between 0 and 65,535. Let’s implement the Vibration(); function which is going to be a void, because it will only perform the code inside, and not return something.

void XBOXController::Vibrate(float left, float right)
{
    XINPUT_VIBRATION vibration; 

    //Invoke memset to zero out the XINPUT_VIBRATION. 
    memset(&vibration, 0, sizeof(XINPUT_VIBRATION)); 

    /*
       According to MSDN Documentation on this, 
       speed of the left or right motor. Valid values are 
       in the range 0 to 65,535. Zero signifies no motor 
       use; 65,535 signifies 100 percent motor use.
    */

    vibration.wLeftMotorSpeed = (int)(left*65535.0f); 
    vibration.wRightMotorSpeed = (int)(right*65535.0f); 

    //Vibrate the controller 
    XInputSetState(XBOX_CONTROLLER_NUM, &vibration); 
}

Now, one final, function we should implement is the GetState(); function which allows us to check if the player pressed A or B etc on the XBOX controller. This one is simple to implement.

XINPUT_STATE XBOXController::GetState()
{
    memset(&XBOX_CONTROLLER_State, 0, sizeof(XINPUT_STATE)); 
    XInputGetState(XBOX_CONTROLLER_NUM, &XBOX_CONTROLLER_State); 
    return XBOX_CONTROLLER_State; 
}

Now we’re done with this simple example entirely written in C++ Win32, so how should we use this code in our main.cpp, easy, I have added the code below.

#include <Windows.h>
#include "XBOXController.h"
#include <iostream>

using namespace std; 

void main()
{
   XBOXController* player1 = new XBOXController(1); 

   system("color 0a"); 

    cout << "Instructions:\n";
    cout << "Press [A] to vibrate left only\n";
    cout << "Press [B] to vibrate right only\n";
    cout << "Press [BACK] to exit\n";          

    while(true){ 	
        if(player1->IsXBOXControlConnected()){
	    if(player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A)
		{  player1->Vibrate(65535, 0); }

		if(player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_B)
		{ player1->Vibrate(0, 65535); }

		if(player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_BACK)
		{ break; }
	}
	else{

		cout << "\nERROR! PLAYER 1 - XBOX 360 Controller Not Found!\n";
                cout << "Press Any Key To Exit.";
                cin.get();
                break;
	}

	delete player1; 
     }
}

Finally, let’s run this code, in my case I have no wireless USB adapter or cable to connect the XBOX 360 controller to my laptop, therefore, I receive the error because it returns false when checking for XBOX controller connection status.


 

Wrapping up

I’m done with this, for now. I think it’s fun to play around with this, since it’s so easy to use the provided API. In addition, I think this code can be further expanded, meaning that we can do more checks and add more functionality. However, most of this code is not elegant or perfect, but it should work, the main idea here is for you to understand the concept, the rest is up to you.
 
But for now, happy coding!
 

First Person Shooter Cameras

In this article I’ll be covering the concepts and what level of math knowledge is required for making a First-Person Shooter (FPS) Camera in games. So let’s get started with some common concepts: pitch, yaw, and roll. Pitch is when the player moves the camera up and down. Yaw is when the player moves the camera from left to right and respectively. And finally Roll is when the player tilts the camera from left to right and respectively,  this rotation usually occurs around the Z-axis.

Camera movements using the computer mouse (Pitch, Yaw and Roll)

 

The FPS Camera functions

In FPS games, the is camera required to do the following:

  • Move forward and backward (Using the W or S keys on the keyboard)
  • Strafe Left or Right (Using the A or D keys on the keyboard)
  • Jump (Using the [space] key on the keyboard)
  • Look around (Using the mouse):
    Pitch (Look up and down), Yaw (Look left or right) and Roll (Tilt left or right)

 

Camera movements using the computer keyboard

Camera movements using the computer keyboard

 

Advanced Mathematics knowledge is required to make an FPS camera

As you already know, all kind of programming will require some mathematics knowledge. However, game programming is a challenging level of programming, and the mathematics required here, goes usually beyond what the average person knows, with other words even the math becomes challenging in the way it is required to be used. Here’s how the axis are used for an FPS camera:

Vectors used to describe the position and orientation of the camera in the world

 

The picture above describes the Euler Angles, and are based on Euler’s Rotation Theorem that any rotation can be described using three angles (X, Y, Z). Another mathematics formula or method to be applied here is Matrix, no I am not referring to Matrix the movie. The matrix in game development is often described as view matrix.

The Matrix

 

In addition to what has been covered so far, you also need the following skills: Geometry, Trigonometry (You only need: sin and cos), Vectors, Matrices, 2D and 3D transforms, Projections, and Transformations between coordinate systems. However, please note that I cannot teach you math here, but I will later post a complete tutorial on how to make your own FPS camera with C++ and we will either be using OpenGL or DirectX.

 

References:
Weisstein, Eric W.
“Euler Angles.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/EulerAngles.html
Weisstein, Eric W.
“Euler’s Rotation Theorem.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/EulersRotationTheorem.html
Weisstein, Eric W.
“Matrix.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Matrix.html
Weisstein, Eric W.
“Trigonometry.” From MathWorld–A Wolfram Web Resource.
http://mathworld.wolfram.com/Trigonometry.html
Weisstein, Eric W.
“Sine.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Sine.html
Weisstein, Eric W.
“Cosine.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Cosine.html
Weisstein, Eric W.
“Geometry.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Geometry.html
Vector: http://content.gpwiki.org/index.php/Vector

 

How to make games

In this article I am going to be covering the process behind making games (or Game Development). And I am also going to cover some additional details, like what knowledge is required, what math skills are required and much more.

What is a game?

Wikipedia defines a game as:

“…is structured playing, usually undertaken for enjoyment and sometimes used as an educational tool.”

My own basic definition:

“A game is more than an activity with a score, a game provides entertainment with an excellent goal to play and complete it.”

Traditionally and generally a game should contain these three basic components:

  • Interactive element(s)  (Objects, which you control  in the game e.g. character)
  • Challenge (The game must have some challenge, it shouldn’t be easy to complete)
  • A goal (A story + ending or Best Game Stats)

It is very obvious that a game must be interactive, and the game must involve some kind of challenge (e.g. a boss with higher level if RPG) and the game must have a predefined goal which the player really wants to achieve.

I’ll give you an example; let’s have a closer look at FlatOut 2™.

 

 

In FlatOut 2™ the interactive component is the car you drive, since you control the speed and control the movement (you turn right or left). The goal in this game is to win as many races as possible, and the challenge is that you have competition all the other cars are programmed and controlled by the computer (i.e. bots). The bots don’t often do mistakes, and this poses a challenge on the player.

The Components of a Game (Basic Level)

In order for us to make a game we actually need to understand the components that make up a game, I’ll explain this on a basic level.

  • The rules of the game (i.e. the basic engine and default choices of the game characters includes more)
  • The Graphics
  • The Sound and additional media

 

The Rules of the Game

The rules are very basic to set, OK, let me explain. I love being a programmer; I love this world and field, because as a programmer you get to be the god of games and software programs. For example, I can set the default rules for any game I make, I can set default points, and Health Points (HP) for any game character, and I get to decide how the character shall look, what skills it shall have etc. wow, this is really working as a god of your own creations.

 

The Graphics

Graphics is really the component that captures the attention of the player. Graphics are very important in games, nobody wants to buy a Text-Based Game nowadays, because, our computers are much more powerful these days, and our PCs allow us to play games with better graphics. Most graphics in games are composed by two distinct types:

  • Sprites
  • Tiles

 

Sprites usually consist of anything that can be moved (e.g. the super Mario character).

Tiles usually make up everything else, the rest of the graphics in the game, or at least other objects which usually are fixed and cannot be move unless blown up by a gun.

 

The Sound and additional media

The sound is very important component in the game, it really gives that little extra feeling, OK, let me explain, if you want to the cinema and you paid for Man In Black 3 (or MIB3) they cinema played the movie for you, but without sound, how would that feel? Exactly, the exact same feeling appears when you play games without sound. However, the sound in games comes in the form of background music and sound-effects, and sometimes additional media as a voice from another game character.

Here’s a clip of the Super Mario Bros (Listen to the sound):

The following article in PDF provides additional details on how early game sound designers engineered their work, In the Loop: Creativity and Constraint in 8-bit Video Game Audio

How to make a game?

OK, so I think we now understand some of the basic components that make up a game. However, now it’s time to make our own game. But in order for us to make a game, we need to check our skills; a game developer must know and understand computer programming. However, do not worry; it is possible to make a game either way, except that one path will differ from another.

 

Implementing the actual rules of the game

Remember the god job? Kidding, but it is almost like that in the world of game development. However, the rules of a game are often best expressed as a sequence of logical operations and condition. Implementing this is easy, but it also depends on the developer, does he/she understand computer programming. It is important to know programming in order to implement the rules of the game.

 

The Choice of Target Platform

There exist a few platforms that are very popular; I think it is important to make target-platform choices. Before we actually get into the details of how to actually make a game, it is important to make some decisions or make a choice (BTW, you can always change your mind). I personally would go for the target-platform that provides very high exposure.

 

 

If I make a game, I want as many people to play it, so they can send me positive/negative feedback with additional suggestions, that way I can improve the game. High exposure allows me to make two editions of the game, for example, the free edition includes a number of features and stuff, while the paid edition includes extra stuff, and gives the player access to new stuff.

 

The Technical Fundamentals of How a Game Works

Player input (Keyboard and Mouse): The player input is really the main force in the game; almost everything the game logic (Game Engine) does is to respond to player inputs in different ways. The input usually comes from Keyboard and the Mouse; however, there are other input devices like a hand control or joystick.

Collision Detection (Objects): Performing collision detection test between two objects can be a very complicated task; it involves math skills and programming including graphics. Here’s an example with two Spheres:


Figure 1: r1 and r2 does now mean r ^ 1 or 2 it simply means radius 1 and 2.

This is called: Bounding Spheres. To determining if two spheres collide is pretty simple, but can be complicated. However, to gain a quick understanding of this problem, let us take a look at what happens when two spheres are touching each other. OK, as we can see in this Figure 1, the radius (r) of each sphere including the definition of the distance for its center to the opposite sphere. Given this information, the distance between the centers would be equal to = r1 + r2. If the distance is greater, the two spheres would not touch each other, but, if the distance isn’t greater, then the spheres would intersect.

Artificial Intelligence: AI can be done; however, it isn’t real AI since the game characters (the creatures or cars in the game not controlled by the player but by the PC, a.k.a. bots) have predefined operations e.g. walk, drive, attack etc. While AI in theory is described as “intelligence” that can learn and do different things.

Camera: The Camera in games works much like a movie camera (like Hollywood). The camera governs what we see on the screen. The game world is often much larger than the screen, so the camera allows us to see the part where we are active in the game. Screen bounds, if the player goes outside the bounds of the screen, the camera will move so we can still see the player.

 

I do not know computer programming (give me directions)

If you do not know computer programming, I will help you, but, with directions, since I cannot teach you programming over Internet. You can make games using C#, C/C++, Java, Ruby or almost any other programming language.

For C# See this:

http://msdn.microsoft.com/en-us/vstudio/hh341490.aspx

http://msdn.microsoft.com/en-us/library/a72418yk.aspx

http://www.csharp-station.com/tutorials/lesson01.aspx

For C/C++ See this: http://www.cprogramming.com/

For a basic library, and since you are a beginner in programming, well, once you learned programming and Object Oriented Programming (OOP), then download Allegro, via this site: http://alleg.sourceforge.net//index.html

 

I know computer programming (feed me with additional tips)

If you already know and understand computer programming, and know OOP, then I’ll provide you with additional tips.

DirectX: http://msdn.microsoft.com/en-us/directx/aa937788.aspx

or OpenGL: http://www.opengl.org/

SFML: http://www.sfml-dev.org/

Additional resources:

DirectX Tutorials: http://directxtutorial.com/Tutorial9/B-Direct3DBasics/dx9B1.aspx

OpenGL Getting Started: http://www.opengl.org/wiki/Getting_Started

Getting Started with OpenGL:

http://www.codeproject.com/Articles/2215/Getting-Started-With-OpenGL

Getting Started with SFML:
http://www.sfml-dev.org/tutorials/1.3/start-vc.php

 

Make a prototype

Once you have a game idea, you should try to draw it on paper, this way you can test your idea, and you can make a prototype of the game e.g. a beta version. Here’s an article about paper-based prototypes: Quick, Easy, and Effective Paper Prototypes. Here is another article, very useful: Prototyping: You’re (Probably) Doing It Wrong.

 

How do you make a good game?

This process is the most difficult part of all. For example, you’ve got your game idea, and you’ve made a prototype, but how do you know if the game is good?

Well, once you’ve been working on a game for a while, it does get difficult to tell, if what you’ve been making a game that is fun. The main reason behind the difficulty; is that being constantly exposed to every minute of working on the game, does not really give you the actual minute to play and enjoy, for example: when you buy a game you will play it right? But when you are building a game, things get different; you spend more time focusing on the project plan than playing the actual game.

The next step is to let as many people as possible, to play your game and let you know what they think about it. Collect as much feedback as possible, and try to remember one thing: “every single piece of deeply constructive negative feedback IS correct”. The people that take the time out to tell you, what they don’t like are right. Of course, there are things they might not like, which you still want the game to have, however, that cannot be changed, unless you really have to.

 

Best of luck!

Well, I have simply covered almost everything in Game Development, or at least a quite large part. And I’ve also covered everything from concept to the actual implementation of the game. Making a game is not an easy process, as you might know by now. It requires time, so you have to allocate time, and be patient. The best advice I can give you, never give up and always try, work hard, talk to people that are in the business, and ask your programming teacher or ask me.

 

Sources:
Screenshot FlatOut 2 (http://screenshots.teamxbox.com/screen/50011/FlatOut-2/)

 

 

Make your own custom C++ ToUpperCase and ToLowerCase functions (Intermediate Level)

Converting between upper case and lower case characters can always be useful, depending on what we want to accomplish. In C++ we normally, include <ctype.h> that provides us with two functions: toupper(); and tolower();

 

Here’s how we would use them:

#include <iostream>
#include <string>
#include <ctype.h> 

using namespace std; 

void main()
{
     string s = "mario";
     string ss = "ZELDA"; 
     for(int i = 0; i<s.length(); i++){
	  s[i] = toupper(s[i]); 
     }

     for(int j = 0; j<ss.length(); j++){
          ss[j] = tolower(ss[j]); 
     } 

     cout << s << endl; 
     cout << ss << endl; 
     cin.get(); 
}

Here’s the result when running this code:
 

 
That’s very simple, isn’t it? Yeah! I think it’s too simple, but that’s me. However, what about making our own tolower and toupper functions with C++, completely customized functions, this is way more fun! We’ve got a challenge ahead, so let’s solve it.
 
I’ll be creating two functions both will return string, I name them, ToUpperCase(); and ToLowerCase(); and they both take one string parameter each:

string ToLowerCase(string text);
string ToUpperCase(string text);

 
To complete these two functions we need to use the American Standard Code for Information Interchange (ASCII) table, which provides a complete list of different characters including the alphabetic ones. In addition, the ASCII table provides the decimal numbers that represent each character. I’ll be using the ACII table found on http://www.asciitable.com/.
 
According to the ASCII table:

Upper Case: 65-90
Lower Case: 97-122
 
The ASCII table is correct, if we declare a char c = 65; and print this, we’ll see ‘A’ in the console window, this means that it is printing an upper case ‘A’, since 65 in the table equals ‘A’.
 
I’ll start by writing the very first function, the ToUpperCase(); function:

string ToUpperCase(string text){
  for(int i = 0; i<text.length(); i++){
     char c = text[i]; 
     if((c>=97)&&(c<=122)){
	 text[i]&=0xdf; 
     }
   }
   return text; 
}

 
Once you’ve written this function (or copied it), hit F5 in Visual Studio to run the program in Debug Mode. Don’t forget to invoke the function like below:

string s = "super mario"; 
s = ToUpperCase(s);
cout << s << endl; 
cin.get(); 

If everything went well, and you didn't encounter any issues while compiling, you should see this:
 

 
Awesome, so it works, we succeeded with the first function. Now lets go in-depth and explain the magic behind the success, yes, I will explain what's happening when we invoke this function and pass a string to it.
 
Let's have a look on our string s = "super mario"; I have added a simplified picture of the string index array below:
 

 
We can easily loop through it with a For-loop. So far, so good, things remain clear and easy. A char data type gives us the ASCII decimal numbers that each single character equals to. First we check for lower case letters, if((c>=97)&&(c<=122)), next we do the magic that converts an lower case letter to an upper case letter.
 
The magic happens right here:

 text[i]&=0xdf; 

But what happens exactly? Simple, and yet complicated to fully explain, &= is a Bitwise AND operator, remember binary and bits? Yes, to explain what exactly happens here, we have to dive deep into the binary world, yeah! Weird huh?
 
If we look in our code again, we see that the first single character in our string index array is 's' and in the ASCII table, the decimal value for 's' is 115. The &=0xdf, 0xdf is a hexadecimal value that equals to 223 (decimal).
 

 
To understand this, you'll have to understand the AND gate and use a Truth table remember from the basic electricity courses in school? The AND gate is easy to understand for example, if A = 0 and B = 0 the output becomes 0, and if A = 0 and B = 1 the output becomes 0, the only time the output becomes 1 is if both A & B equals 1. I also marked the zeros with red rectangles to highlight a pattern that simplifies the understanding of this. The number 83 in the ASCII table represents the upper case 'S'.
 
Now that I've completed the ToUpperCase() function, I will write the next function, ToLowerCase() which converts upper case letters to lower case letters. This is easy, now that we made the first function.

string ToLowerCase(string text){
   for(int i = 0; i<text.length(); i++){
      char c = text[i]; 
      if((c>=65)&&(c<=90)){
	 text[i]|=0x20; 
      }
   }
   return text; 
}

There are some differences between this function and the previous one we wrote, for example, we now check for upper case letters, if((c>=65)&&(c<=90)) and the magic, text[i]|=0x20 now uses the Bitwise OR Assignment Operator |= which differs from the previous Bitwise operator.
 
Once you've written this function (or copied it), hit F5 in Visual Studio to run the program in Debug Mode. Don't forget to invoke the function like below:

string s = "JAK AND DAXTER"; 
s = ToLowerCase(s);
cout << s << endl; 
cin.get(); 

If everything went well, and you didn't encounter any issues while compiling, you should see this:
 

 
Yeah, again even this function succeeded. However, I want you to understand the magic behind it, so I made another image that explains the Bitwise OR operator:
 

 
To better understand this, let's have look in our code again, we see that the first single character in our string index array is 'J' and in the ASCII table, the decimal value for 'J' is 74. The &=0x20, 0x20 is a hexadecimal value that equals to 32 (decimal). For upper case 'J' to become lower case letter, 'j' its value must become 106, and that's what text[i]|=0x20; does. This can easily be explained by the image above.
 
The Bitwise OR operator is simple to understand, very straight forward, just think of the OR gate, if A = 0 or B = 0, the output becomes 0, and if A = 1 or B = 0, the output becomes 1. The big difference between the OR gate and AND gate is that, if A = 0 or B = 0 then the output becomes a 0, and that's the only time in the case of the OR gate. For the AND gate, the only time the output becomes 1 is if both A and B equal 1, else it's simply 0.
 

Wrapping up, for Now

I’m not quite done with this, I think it's fun to play around with it, especially the Bitwise operators which allow us to accomplish a lot. I bet there's someone that can make other functions using the inner code from one of these two functions I made. In addition, I think it's useful for programmers to sometimes play around with code at this level of difficulty, despite experience.
 
For now, happy coding!
 

Lecture 1: Introduction to C++

At its very core, the personal computer (PC) is just a central processor unit (CPU) with some memory (RAM), capable of executing a tiny set of instructions like, “store 255 in memory location 0xff6900h.” However, with an operating system (OS), a high-level programming language, an integrated development environment (IDE), compiler, and some programming knowledge we’re capable of doing much more with a PC.

 

What is C++ ?

C++ is a multi-paradigm, statically typed, case sensitive, high-level programming language. The C++ birth dates back to year 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. C++ inherits the C language, however, supports object-oriented programming (OOP). Stroustrup began working on a project he called “C with classes”, which as the name implies it supports OOP without losing the portability, speed or low-level functionality that C provides. C++ today is immensely popular across the world, and it is mainly used for its speed and/or the low-level features it provides.
 

The Compilation Process

A program goes from C++ source files into processor instructions as follows:

Compilers and assemblers emit object files containing the generated binary code and data for a source file. The Linker then links together multiple object files into one; and the loader takes the produced object files and loads them into memory.
 
An object file is the real output from the compilation phase that represents an incomplete copy of the program. One single C++ source file expresses the whole program, while in the case of multiple C++ source files, each C++ source file express a piece of the program, once compiled into an object file, the outputted object file has some markers indicating what pieces it depends on. The Linker takes all the emitted object files the compiled libraries of predefined code that they rely on, and links them together into the final program, which can then be run by the OS.
 
The Compiler and the Linker are just two simple regular programs. The first step in the compilation phase is known as parsing—which the compiler reads the source code file(s).
 
The main reason C++ code runs far faster than code in many more recent languages, is because all these steps are performed ahead of time, before you start running a program. In some programming languages, these steps are performed during the execution process, which takes time.
 
In addition, C++ actually adds an extra step to the compilation process, the code runs through a preprocessor. The preprocessor is a program that is invoked by the compiler to process code before compilation. Thus, the modified illustration becomes:

 

Hello World

It is an honer to start this paragraph with the traditional “Hello,world!” program as an entry point into the basic features of C++.

// A Hello World Program
#include <iostream>

using namespace std; 

int main()
{
    cout << "Hello World" << endl; 
    cin.get(); 
    return 0; 
}

 

Line-By-Line Explanation

  1. The very first line at the top of our Hello World program is a simple comment.
    // A Hello World Program

    Comments are ignored by the compiler, and are used to explain the non-obvious things going on in the code. Comments exist in two forms:

    // Single-line comment
    /* Multiple-lines comment */

    In conclusion, comments should be used to document your code and explain different parts of the code.
     

  2. On the next line we find our very first pre-processing directive, #include. All pre-processing directives start with a hash sign (“#”). Pre-processing directives are used to change what code is actually being compiled.
     #include <iostream>

    #include tells the preprocessor to treat the contents of a specified file, in this context the ‘iostream’ file, as if those contents had appeared in the source program.

  3.  

  4. Below line 2, comes an interesting piece of code, a namespace is used.
    using namespace std;

    The namespace keyword is used to organize code and provides a unique way to share identifiers. The using namespace [something]; is used to avoid the constant usage of the scope resolution operator (::)—for example, in the Hello World code example, the using namespace std; tells the compiler that it should look in the std namespace for any identifier that we have not defined. If we do this, we can omit the std:: prefix when writing cout, this is the recommended practice in general when writing C++ code.

  5.  

  6. Finally, our very first program function, int main() { . . . }—defines the entry-point that is executed when the program starts up. Everything between the curly brackets ({ }) represent multiple statements in a code block. I’ll be covering more about the syntax in the next few lectures.
  7.  

  8. There are three statements inside the main() function:
    cout << "Hello World" << endl;
    cin.get();
    return 0;

    Statement 1: cout is used to output a string (text) to the console. Std:cout is an object of the ostream class that represents the standard output stream. insertion operator (<<) is used to pass in a string or any other variable that is then outputted to the console on the screen. The endl; ends the line by inserting a new-line character (‘\n’ a.k.a. escape sequence).
     
    Statement 2: The Std::cin is the opposite of the cout, cin is an object of the istream class that represents the standard input stream. However, cin is used differently in this context, I am accessing a function, the get() function in the cin object. The cin.get() forces the program to wait for the user to enter a key before it can close, and you can see the output of your program.
     
    Statement 3: The return 0; statement indicates that the program has completed successfully.

 
 
That’s a lot of information, huh? Do not worry, I’ll be explaining more in coming lectures about C++. Till next time, enjoy this lecture and have fun!
 
Cheers,
Fisnik
 

Introducing the F# Programming Language

F# (pronounced “F Sharp”) is a functional programming language built into the .NET—just like C#, J# and Visual Basic. Furthermore, F# can take advantage of the same core .NET libraries as the three mentioned languages. F# is a bit different from the three mentioned programming languages; in fact, F# has inherent technical strengths as a multi-paradigm programming language, uses type interference, supports LINQ, provides F# interactive visualization and includes all the important elements of functional programming.

 

F# was originally started at Microsoft Research, Cambridge in 2005. The Microsoft Research (MSR) team continues to improve F#, and continues its partnership with other teams across the company and with—external open source organizations, researchers, and companies. F# is currently shipped with Microsoft Visual Studio 2010 by default, however, is also included in Microsoft Visual Studio 2012.
 

 

Basics

Here are a few basic lines of code I will explain:

open System 

let msg = "Hello World" 

printfn "%s" msg 

Console.ReadKey() 

When compiled and executed in debug mode this code will print out ‘Hello World’ in a console window.
 
The open works like using in C#, we tell it what namespaces we want to open, in this example I used the standard System namespace. The let keyword is used to bind expressions, or to define values or function values for one or more names. The printfn prints a formatted value to stdout, and adds a newline (‘\n’); The format styling looks pretty much like C‘s format styling, consisting of strings with % markers indicating format placeholders.
 
Declaring variables is very straight forward, F# does not need to have the data type predefined for it i.e. int i = 0; here we tell it that we want to declare an int. In F# you don’t have to do it this way, it detects this by value.

let i = "" // string 
let i = 'a' // char
let i = 0 // int 
let i = 0.0 // float
let i = true // bool
let i = "text"B // byte[]

 
Creating functions is very easy too, however, can be very painful and dirty first time, especially, if you like me are used to declaring functions like this:

int multibytwo(int x) { return x * 2; }

well this does not work in F# unfortunately, and it will seem very wired, but here’s how you write the same function in F#:

let multibytwo (x : int) = 2 * x

With just a few examples of F# code we see the difference between it and C# and many other programming language that share the .NET Ecosystem.
 

Math fun with F#

F# has been suggested to be used to solve math problems, or try out different math functions and equations. Here’s the basic code for multibytwo (x : int) = 2 * x :

open System; 

let multibytwo (x : int) = 2 * x
let v = multibytwo(500)

printfn "Equals %d" v

Console.ReadKey(); 

 

 
Here’s another interesting example, N^2:

let square x = x * x

let numbers = [0 .. 10]

let squares = List.map square numbers

printfn "N^2 = %A" squares

 

 
The second code example can be a bit complex to understand, the very first line is very obvious, so I will explain the second, let numbers = [0 .. 10] is is an immutable linked list we tell it that we declare a list of numbers 0 through 10, next, let squares stores the result from List.map square numbers. I recommend reading this when it comes to the List.map (http://msdn.microsoft.com/en-us/library/ee370378.aspx).
 

F# Interactive for Visual Studio

The F# Interactive Console (FSI) is a tool known as a Read-Evaluate-Print-Loop (REPL). This simply means it accepts F# code directly, and compiles and executes it, then prints the results. This allows us to quickly and easily experiment with F# code snippets without the need to create completely new F# projects or build a full application just to print out some results.
 
To launch the FSI tool simply highlight some code and press ALT+ENTER, the FSI windows will immediately pop-up in Microsoft Visual Studio.
 

 

Conclusion

Finally, after playing around with F# and writing this tutorial as part of the tryout, I think I start to like the F# programming language. The F# programming language in my opinion simply provides a better way to deal with different mathematical problems, and solve them. From what I know when I heard of F# several years ago, is that it was proposed to be used by scientists to solve scientific problems, and this is very interesting to me, especially, since I myself am very interested in science and mathematics. In short, I think F# is something worth to learn; sure it takes time and can be painful in the beginning, however, things become clearer as you learn more, so I recommend it and give it a try.
 
 

Computers allow kids to better understand and learn math

Back in 2010 at TED talks, Conrad Wolfram  spoke about math in schools, and teaching kids real math with the help of using computers (Conrad Wolfram: Teaching kids real math with computers) this video was to me very interesting, so I decided to do some study, and also decided to write this article to present some of my findings, ideas and results.

 

Teaching math in school

Mathematics in school is simple when you first time start doing math and learning it. However, as you grow older, in school you also study higher levels of math, and these levels become challenging in some cases. There are three factors that impact the way you learn math, these are:

 

  1.   Your ability to quickly calculate and play with numbers
  2.   The way your teacher is teaching math during a math session
  3.   Your own interest in learning and understanding math

 

Note: Above I only included three factors, but there are a lot more factors that impact the way we learn math.

 

Math levels

The math is divided in levels, and each level is unique. Basic level is where we all start, and that is obvious, nobody can start at the last level, even Albert Einstein had to start from basic level.

 

  1. Basic Math
  2. Pre-Algebra
  3. Algebra
  4. Geometry
  5. Algebra 2
  6. Geometry 2
  7. Trigonometry
  8. Pre-Calculus
  9. Calculus
  10. Advanced Calculus

 
There are probably a few more levels I haven’t included here.

 

Computers are great calculators

Personal Computers (PCs) are great calculators and are some of the fastest calculators in the world; of course a modern calculator uses the same technology, the Central Process Unit (CPU), one modern and much known CPU is the Intel® processor. The Arithmetic Logic Unit (ALU) is one of the essential and key features in a CPU, which allows the CPU to perform arithmetic operations Addition, Subtraction and so one. Beside the arithmetic operations, the ALU allows the CPU to perform basic logical operations such as AND, OR, NOT, XOR (exclusive or) and so one.

 

Humans have created a set of CPU instructions that can be used to tell the CPU what to do; this language is called Assembly (ASM). ASM has been around for a long-time, and is common in many areas in the software world. ASM is still used to build boot loaders in Operating System (OS) development. However, the computer sees everything in 1 and 0 or in binary form, but I would like to demonstrate how a CPU-instruction in ASM will add two numbers, I will be using C++ programming and perform inline ASM.

 

I will be using the x86 (32-bit) CPU registers to store data. The EAX, EBX, ECX and EDX are the four general registers. I will keep this very basic, with a lot of details.

 

 

This code may seem advanced, but is quite easy to understand, okay, I’ll explain. Let’s examine what really happens, we jump to the int declaration.

 

i. I start by declaring three int variables they get a default value zero.
 

int valueA, valueB, result = 0; 

 
ii. Jumping one line, valueA equals 5 and valueB equals 10.
 

valueA = 5; 
valueB = 10; 

 

iii. Then we enter the inline code of x86 CPU assembly instructions, we use the MOV instruction to move data from valueA to EAX, and we move data from valueB to EDX (Figure A explains the first move).

 


Figure A: The MOV instruction makes EAX as the destination for the data variable valueA contains. This is exactly the way the MOV instruction moves data, which can be defined like this: MOV destination, data.
 

 

iv. Then we perform addition, by using add eax, ebx which means EAX = EAX + EDX so we store the end result in EAX register.

 

v. Next, we store the data which EAX contains in the result variable, and finally we XOR (clear) the EAX and EDX registers.

 

This is another example of how a CPU performs arithmetic calculations. I am glad I was able to provide a demonstration and explanation regarding this.

 

Programming helps understanding and learning math better

Mathematics appears to be a great subject, but as you move further and begin learning and experimenting with higher levels of mathematics things can get really messy. When   equations and formulas including different theories and rules are involved in mathematics, this will directly make things harder for anybody. However, a key solution to better learning math rules, theories, equations, and formulas is by learning basic programming. If every child started learning basic programming at the age of 10 we would never experience math issues in school, no matter how advanced and complex the math would become at least 90% percent or more of all the students would hopefully pass the test, all this thanks to programming. Children do not need to learn Object Oriented Programming (OOP), they only need the basics (understanding code, data-types, and logic if-else statements), and to learn how to program the application so it can receive input (argument) and provide output (print to the screen) nothing else.

 

Here’s how programming helps students understand and learn math faster and better. If you know programming, you can make a function in your program that calculates for example the slope of a line. But to make this function you have to learn and understand the formula, the rules and how it is used correctly the mathematical way. However, I will provide two examples, one which is very basic and the other one which is a bit complex, but yet easy as well.

 

Programming example 1:
Build a program that calculates total price per mile a taxi driver, drives a person. Remember: The taxi company has a fixed price which every customer has to pay the fixed price (f) which equals to $20 USD is added to the price $4 USD / mile.

 

We have three things to keep in mind:

 

  1. Price per mile.
  2. How much a customer has to pay?
  3. Remember that 1 Mile equals 10 km

 

Now this is going to be very simple. But it will allow any student to better remember and understand how this works.

 

This is the equation or formula which I have setup:

 

 

Variables:
T = Total cost.
P = Price
F = Fixed price
X = Mile(s)

 

Calculation by either hand on paper or writing it in word like this may seem like a long calculation, but is very short.

 

T(x) = f + px
T(5) =  20 + (4 * 5)
T(5) = 20 + 20
T(5) = 40

 

Here’s the code in C++:
 

int T(int x); 

//$4 USD per mile. 
int p = 4; 
//$20 USD.
const int f = 20;  

void main()
{
   int Total = 0; 
   Total = T(5); //5 miles = 50 km. 
   cout << "The customer has to pay: $" << Total << " USD" << endl; 
   cout << "" << endl; 
   system("pause"); 
}

int T(int x)
{
    return f + (p * x);  
}

 


Figure B: The computer did the calculation, but I had to program the software so it can do what I want it to do. This allows me to learn more about the rules, and allows me to determine whether my equation or formula works.

 

 

Programming example 2:
In this second programming example, we will be looking at the linear equation, slope and m interception with the Y-axis.

 

We have two things to keep in mind:

 

  1. Remember the equation: y = mx + b
  2. Remember that b = y-axis  intercept.

 

 

Variables:
M = slope
B = Y-axis intercept
Y = The total value

 

 

 

Find M-value:

 

 

 

m = y2-y1/x2-x1
m = (3-2)/(2-1)
m = 1

 

y = 1x + b
y = 1x + 1
y = (1 * 2) + 1
y = 3

 

Test our calculation:
3 = (1 * 2) + 1

 

Here's the code in C++:
 

double Slope(double y1, double y2, double x1, double x2);  
int Y(double m, int x, int b);

double m = 0; 
int x, y, b = 0; 

void main()
{
    cout << "Find the Y-axis interception value: "; 
    cin >> b ;
    cout << "\n" << endl; 
    cout << "Calculating..." << endl;
    m = Slope(2, 3, 1, 2); 
    y = Y(m, 2, b); 
    cout << "Y = " << y << endl; 
    cout << "" << endl; 
    system("pause"); 
}

//Note: Slope function works only when two known points are passed in, 
//single point is not supported by this function. 
double Slope(double y1, double y2, double x1, double x2)
{ 
    y2 = y2 - y1; 
    x2 = x2 - x1;

    if(y2 == 0 || x2 == 0)
    { return y2; }
    else{
      return y2 / x2; 
    }
}

int Y(double m, int x, int b)
{
    return (m * x) + b; 
}

 


Figure C: Our program calculating the slope and the Y for us.

 

Conclusions

I personally think that the nation that first applies "teaching programming" in school, and I mean children start doing basic programming at the age of 10 will increase their economy and produce a lot of smart people. However, this is one of the reasons governments all over the world shall demand that this becomes a reality, because programming covers math, logic thinking and much more. Mathematics has not been an easy subject in school, and that is because of the levels and each individual's ability to play with numbers, to understand equations etc. But for the coming future, I think programming will play a key role in combating the math problem we see in schools in many parts of the world. The time to change is now, so demand for this change today, for a better tomorrow.

 

Additional information and resources:
Albert Einstein Biography: http://nobelprize.org/nobel_prizes/physics/laureates/1921/einstein-bio.html
The Arithmetic Logic Unit: http://www.windowsnetworking.com/articles_tutorials/arithmetic-logic-unit.html
Linear Equation: http://mathworld.wolfram.com/LinearEquation.html
Slope: http://mathworld.wolfram.com/Slope.html
Slope-Intercept Form: http://mathworld.wolfram.com/Slope-InterceptForm.html