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_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. 

   //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); 
	      cout << "The XBOX 360 controller is connected!" << endl; 
	      cout << "The XBOX 360 controller is disconnected!\nPlease check your XBOX 360 controller again!" << endl; 


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)); 
    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";          

	    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; }

		cout << "\nERROR! PLAYER 1 - XBOX 360 Controller Not Found!\n";
                cout << "Press Any Key To Exit.";

	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: pitchyaw, 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


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: GeometryTrigonometry (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.


Weisstein, Eric W.
 “Euler Angles.” From MathWorld–A Wolfram Web Resource.
Weisstein, Eric W.
 “Euler’s Rotation Theorem.” From MathWorld–A Wolfram Web Resource.
Weisstein, Eric W.
 “Matrix.” From MathWorld–A Wolfram Web Resource.
Weisstein, Eric W.
 “Trigonometry.” From MathWorld–A Wolfram Web Resource.
Weisstein, Eric W.
 “Sine.” From MathWorld–A Wolfram Web Resource.
Weisstein, Eric W.
 “Cosine.” From MathWorld–A Wolfram Web Resource.
Weisstein, Eric W.
 “Geometry.” From MathWorld–A Wolfram Web Resource.

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:

For C/C++ See this:

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:


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.


or OpenGL:


Additional resources:

DirectX Tutorials:

OpenGL Getting Started:

Getting Started with OpenGL:

Getting Started with SFML:

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.

Screenshot 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; 

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

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]; 
   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; 

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:


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]; 
   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; 

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; 
    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.

    1. 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.

    1. 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.
  1. There are three statements inside the main() function:
    cout << "Hello World" << endl;
    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!


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.


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

open System 

let msg = "Hello World" 

printfn "%s" msg 


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 letkeyword 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


Here’s another interesting example, N^2:

let square x = x * x

let numbers = [0 .. 10]

let squares = 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 square numbers. I recommend reading this when it comes to the (

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.


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 ANDORNOTXOR (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:



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; 

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.



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; 

//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; }
      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.


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:
The Arithmetic Logic Unit:
Linear Equation:
Slope-Intercept Form: