This tutorial is the first in a series of basic programming tutorials that aim to introduce the potential reader to the art of programming through the C++ language.The language choice is because C++ is a personal favorite and exposes almost all of the low level operations to the programmer, hence giving him better understanding of what is happening inside a computer which I believe is of utmost importance to someone just beginning to learn. This goes out to all the universities which begin teaching programming with Java robbing the new student of his chance to actually comprehend how a computer works.
Of course as they say C++ allows yourself to shoot yourself in the foot quite easily and can cause a lot of grief to the uninitiated user. So this tutorial series is here to bridge that gap and provide that guidance to the programmer. This tutorial is extremely basic and would only be of use to people not knowing anything. Consider yourself warned and read no further if you have any basic skill of C++ or programming.
Tutorial Prerequisities
- If you have any previous knowledge of programming in C++ skip this tutorial.
- No previous knowledge of programming is assumed
- All that is required is will to learn!
Tutorial Goals
- Introduce the reader to the art of programming
Tutorial Body
Let's start from the very basics. Your computer's processor, only understands a set of instructions in 0 and 1s. These instructions differ from processor to processor and they are generally called the Assembly or machine language of the processor. The most common processor architecture and hence the most common instruction set is the x86 architecture. What all Programming languages do is that with the help of a program called the compiler they compile your program from the language you wrote it in, into assembly language. This happens in 3 steps:
- Compiling and creation of object files
- Linking of object files
- Final creation of the executable
Normally the compiler can be called from the command line but to make matters easier we will be using a piece of software called an Integrated Development Environment (IDE). I will showcase how to use my favorite IDE called Codeblocks. It is open-source and multi-platform and quite light-weight compared to other alternatives. Go to Codeblocks download page now and download the latest version suitable for your platform. Choose the option that includes the MinGW compiler in the installation.
The MinGW compiler, also called GCC is an open-source compiler for the C/C++ languages. It is included in the installation so you don't need to specify any settings. When the download is finished proceed to installation and when this is also done launch CodeBlocks.
Go to File-->New-->Project. In the dialogs that follow choose a name for your project and other than that just keep the defaults(Choose an empty Project). Go again to File-->New-->Empty File and this time create a file called main.cpp. This will be the main file of our program. Some clarification is needed here. The file you just created is called a source file. The source files are your program, you can think of them as the blueprint of your program. There are two types of source files:
- Source files:These files have the .cpp suffix for C++ and .c suffix for the C language. They contain the implementations of functions, classes, structure and generally all the other structures you are about to get familiar with
- Header files:These files have the .hpp suffix for C++ and .h suffix for the C language, but most people use the .h suffix everywhere. They contain the declarations of everything inside your program.
We will see more details about both of them below.
Now paste the following into main.cpp
#include <stdio.h> int main(int argv,char* argc[]) { //Prints to the standard output printf("I think therefore I am...the world is now mine for the taking!!!"); //returns the return code of the program, we just return 0 return 0; }
This should all be very new to you so I will analyze it line by line.#include <stdio.h>
This line introduces the #include directive. It is called a preprocessor directive, because it is used by something called the C preprocesor. The C preprocessor analyzes the code before and during compiling and finds and executes these directives. All preprocessor directive start with the sharp sign #.The #include directive basically includes a header file. A header file encased in < and > is a system header file. These are mainly the C standard library located inside your compiler folder. But if you also download and properly interface a third-party library with your program (we will see how in a next tutorial) the header files of that library will also be encased in < and >. The stdio.h header file contains many standard library functions and you can see more details about it here.
int main(int argv,char* argc[]) { ... }
This is a function. It is a basic building block of any program and any programming language. The part before the brackets int main(int argv,char* argc[]) is called the function's signature. This is what uniquely identifies the function inside your program. The first keyword int, is what value/object the function returns. It can be anything. Here it is an int which means an integer. It means a number ranging from -INT_MAX to +INT_MAX. The value of INT_MAX depends on your system.
The second keyword before the parentheses is the function's name. This is therefore the main function.
Inside the parentheses we have the parameters that the function takes separated by comma. This function takes two parameters, one is an integer and the other is something called a pointer to an array of characters. You don't need to understand it right now, it will be thoroughly explained in a future tutorial.
Functions normally have a declaration and an implementation. It is good programming practice to declare the function in a header file and then implement it separately in a source file. We will see how to do so below. But there is something very special about this function and this is why declaration and implementation are together in the source file. This is the main function. Every program must have a main function and it should look like the above. The main function is the place where your program starts running from. No matter how many functions , classes and other stuff you have defined this is the part that runs when you execute your program.
//Prints to the standard output printf("I think therefore I am...the world is now mine for the taking!!!"); //returns the return code of the program, we just return 0 return 0;
This is what we call in programming, a "Hello World" program. By some unwritten rules it should be the first thing you ever program in any new language. I like unwritten rules like that so here it is. A program that prints something to the console. Let's analyze it a bit.
What follows after // is a comment. A comment is text that can not get executed, has nothing to do with the program and is just there to help and document. Comments in C++ can have two forms as you can see below.
//This is a comment /* This is also a comment*/ /* This type of comment can span as many lines as you want */
The // is a single line comment, but the /* opens a comment area that can span many lines and ends when it encounters a */. Coments are Good! Writing commented code is good! It might seem silly to you at first but you have to be explaining what you do in your programs. The reason is simple. When you go back to your code months later you will most probably remember nothing and having someone (past you in this case) explain what is what, may save you out of a serious situation. I believe that it is good to develop good programming practices from the very start so I strongly encourage you to use comments in the code you write. Of course there is doing and there is over-doing. Over-commenting is also a problem so don't use comments when it's clearly obvious what each piece of code does. This avoids cluttering of the code.
printf(".."); is a standard library function that prints to the standard output. It is an extremely useful function which provides the user with many options. We will use it many times in the future and so if you would like to learn more about its usage visit the documentation page here. What it does is print the string of characters encased in " " to the standard output stream. What is the standard output stream? By default it is the console. It can be changed but that we might see in a future tutorial.
Finally return 0; returns the value that the function mentioned it would be returning (remember, int main()?). We don't need it for anything now so just ignore it
Since we explained what each line does let's actually compile and run our program. Go to Build->Compile and Run or just press F9 key and the program will ... well ... compile and run! Notice how it just printed out what we had in printf() to the console?
With the "Hello World" out of the way let me introduce some of the basics of the language.
int i_var = 5; short s_var ; char c_var = 'a'; bool b_var = true; float f_var = 0.3; double d_var = 0.00021;
The above are just some primitive variables. As you can see, a variable is declared by the variable type keyword, followed by the name. In the declaration you can either assign a value as in the first line or not, as I am doing in the second line. Just like anything else in C++ declarations end with a semicolon ';'. A short is just like an int with the only difference that it takes 2 bytes instead of 4, hence saving space but also having a smaller range of integers it can represent. A char can contain a character. To assign a character to something you have to encase the character in single quotes ' '. A char is represented by 1 byte so it can represent any of the 255 ASCII characters. A bool is just a binary value variable. It can have two values. True or false, 0 or 1. A float is represented by 4 bytes and inside it you can save any floating point number with certain precision. A double is just like a float with the difference that it takes 8 bytes and can represent floating point numbers with a lot more precision.
Let's do a small example now. Let's create our very own function. We will follow standards and separate declaration and implementation. Go to File-->New-->Empty File and create "MyStuff.h". Of course you can replace MyStuff with any name you want. Inside paste the following:
#ifndef MY_STUFF_H #define MY_STUFF_H //This function checks if a number n is even //It returns true if it is and false otherwise bool isEven(int n); //This function returns the factorial of a number int factorial(int n); #endif
Let's analyze the above line by line. In the very start you see two preprocessor directives you have never seen before.
#ifndef MY_STUFF_H #define MY_STUFF_H ... #endif
It is good practice to encase any header file with this. These are called include guards. They make sure that your header file won't get included more than once by different files when it's not needed and hence won't have issues while compiling. The #ifndef is a conditional directive that just asks if the following keyword is not defined. If it is not defined then all that is between the #ifndef and #endif directives are compiled. If it is defined then nothing is done since the whole header file is encased inside this #ifndef. What this actually accomplishes is that if the header file has been compiled and included once and some other file tries to include it, it won't compile twice.
Following the include guards are the declarations of two functions. Nothing new here. Just note that this is the proper way to declare functions. Their declarations is in the header file and their implementation will be put in a source file with the same name(See below).
Now go to File-->New-->Empty File and create MyStuff.cpp. Here I would like to teach you a small trick about Codeblocks. If you have a source file or a header file without a corresponding source/header of the same name then you can Right Click on the tab of the file and choose the Swap Header/Source option as shown in the picture.
This will create the new file if it does not exist and it will open it if it already does exist. So now inside the source file paste the following:
#include "MyStuff.h" //This function checks if a number n is even //It returns true if it is and false otherwise bool isEven(int n) { if(n%2 == 0) { return true; } return false; } //This function returns the factorial of a number int factorial(int n) { //Remember that the factorial of a number is nothing but //the number multiplied with all the numbers coming before it int ret = 1; while(n > 0) { ret *= n; n--; } return ret; }
Lets check what's new here. As you might have noticed the source file includes its header file. This should always happen in a header-source file combo. The reason is that the source file should know where the declarations of its functions are.#include "MyStuff.h"
Moreover notice the double quotes "MyStuff.h". Unlike the system header files of the standard library which is encased in < and > since this is a header file that you have created you have to encase it in single quotes.
Now let's look at the isEven() function.
bool isEven(int n) { if(n%2 == 0) { return true; } return false; }
As you can see from above it takes an integer, which we called n and returns a bool variable. Basicaly we chose the bool variable type since
a function which answers if a number is Odd or Even only needs a yes or no answer. So a bool is the right choice. We could have made it return an int but then it would be a waste of resources now wouldn't it?
The above code also introduces a new statement. We see the if statement for the first time. An if statement is pretty simple. The syntax is:
if(condition1) { ... } else if(condition2) { ... } else if(condition3) { ... } .... else { .... }
Inside the parentheses you should input the condition and if a condition is met then what is inside the brackets executes. If not the program jumps to the next else if() and checks the condition. This repeats until the last else (if existing) is found. A condition can be anything that can be reduced to a boolean statement. A yes or a no. Following are some examples of boolean conditions.
bool flag1 = true; bool flag2 = false; int var = 5; if(flag1) {} if(flag1 == true){} if(flag1 && flag2){} if(flag1 || flag2){} if(!flag1){} if(var > 5) {} if(var >= 5) {} if(var < 5){} if(var <= 5 ){}
In line 5 and line 6 the conditions are the same. Line 5 is just an abbreviation of line 6.That condition will check if flag1 is true.
Line 8 checks if both flags are true. If and only if both flags are true will the whole condition be true. This is accomplished by the logical AND operator '&&'
Line 10 check if either flag1 or flag2 is true. If any of them is true then the whole condition will be true. This is accomplished by the logical OR operator '||'
Line 12 checks if flag1 is not true. If and only if flag1 is not true will the whole condition be true. This is accomplished by the logical negation operator '!'
Line 14 checks if var is greater than 5 while line 15 checks if var is greater or equal to 5. This is accomplished by the '>' and '>=' operators respectively.
Line 17 checks if var is less than 5 while line 18 checks if it is less than or equal to 5. This is accomplished by the '<' and '<=' operators respectively.
The above sums up some of the basic boolean conditions you can encounter in C++.
Going back to out original example function we see
if(n%2 == 0)
Here is a never before seen operator. Namely the '%' modulo operator. This performs the mathematical mod operation which can be quite simply described by: "We divide n by 2 and the remainder of the division is the result of the modulo operation". So in our case if the remainder is 0 , which means that n is divisible by zero then the number should be even. Hence we return true. By returning from a function the function exits so the remaining of the function body does not execute. In the case that it is not even, the function will never enter the if brackets and will jump directly to returning false. In such a simple way we have a function that returns if a number is even or odd.
Now let's take a look at the factorial function.
int factorial(int n) { //Remember that the factorial of a number is nothing but //the number multiplied with all the numbers coming before it int ret = 1; while(n > 1) { ret *= n; n--; } return ret; }
It takes an integer and returns its factorial, which is also an integer. So in other words it takes an int as a parameter and returns an int. First of all we declare an int called ret and give it the value of 1. This will be the return value of the function. Following that we have something new!
while(n > 1)
This is the while statement. It is one of the 3 loop statements offered by the C++ language. The while statement allows us to loop while a condition is true. This condition is stated like in the if statement inside parentheses. In this case the portion of code inside the braces gets executed while n is positive and greater than 1. In the code box below you can see the 3 different loops statements and their syntax
//the while loop statement, loops while the condition is true while(condition) { } //the do while loop, executes the code inside the braces at least once, and then starts looping for as long as the condition is true do { }while(condition); //the for loop has 3 fields separated by a semicolon. In the first field you declare or initialize an already existing variable //In the second field you give the condition we require for this loop to be running //In the third field you can add any primitive operation that you would like to apply in every iteration to a variable. for(int i =0; i< n; i++,j++) { }
Going back to the factorial function, inside the while we have two new operators. They are acting on the left side of the operator and are just abbreviations of common mathematical operations. Let's see which these are:
- v*=2 equals v = v*2
- v/=2 equals v = v/2
- v+=2 equals v = v+2
- v-=2 equals v = v-2
Additionally n--; and n++; means that n is decreased/increased by 1. It is the same as n-=1; or n=n-1;
I hope you understand what is happening inside this while loop but just in case you did not I will explain. The returned result which has been initialized to the value of 1 gets multiplied by the given n. And then n gets decreased by 1. This process continues until n gets equal to 1. By that time ret will have been multiplied by all number from n to 2 and hence we will have obtained the value of the factorial of n. As simple as that!
Now that we have made our very own functions it is time to use them for something. Go back to main.cpp and replace it with this code:
#include <stdio.h> #include "MyStuff.h" int main(int argv,char* argc[]) { int e = 16; //Prints to the standard output if(isEven(e)) { printf("%d is an even number\n",e); } else { printf("%d is an odd number\n",e); } printf("The factorial of %d is %d\n",5,factorial(5)); //returns the return code of the program, we just return 0 return 0; }
This is the new main part of our program. You will immediately notice that we have included the header file which contains the newly created functions. Moreover you might notice a kind of strange use of printf. If you go to the printf documentation page you will see a good explanation of all the various parameters and usages of this powerful function. In the above code we are giving variables (or even functions, which basically means run the function and give the returned result as a parameter to printf) to printf and it prints their values.
This is done through the %d token that we put inside the string of characters. Printf scans the string and replaces the %d tokens one by one with the given integer variables which were passed to printf. Of course printf has many tokens and many options for values other than integers but I will leave that for you to study by checking the documentation page. You have to get used to reading function documentations if you are going to get into the programming world :)
So what does this program do? It just checks if e is even using the function we created and prints the corresponding result to the console. Right under that it calculates and prints the factorial of 5.
This tutorial is already too big and somewhere here I think it is wise to take a break before proceeding to part two. This was an exhaustively detailed guide to programming using C++ for someone who would be interested to learn but has never had any contact with programming before. An absolute beginner. In this tutorial the basics of the C++ language including and up to functions were taught. The reader should now be familiar with the basic operators of C++, function declaration and usage, the different types of variables, conditional statements and loop statements. Finally the user should be familiar with how to use the Codeblocks IDE and the GCC compiler to compile a C++ program.
Exercise for the Reader
As an exercise try to implement 3 additional functions:
- A function that will multiply two numbers
- A function that will find out which of two numbers is the biggest one
- A function that will find the sum of the first N integers. You can have n as a parameter to the function.
The usual disclaimer applies to this tutorial of course. I am just a guy who writes tutorials on his free time so it is quite possible that there might be mistakes or omissions. I would be very grateful if you found them and pointed them out to me by mailing me at: lefteris _atmark_ realintelligence _dot_ net . You can also email me with any comments or questions you might have about the tutorial.
As soon as Tutorial part 2 is written a link to it will be posted right here.
Post new comment