Tuesday, May 20, 2008

C++, Setting up your computer and writing your first program.

First of all we'll introduce some basic C++ terminology. It is important to learn good terminology in order to understand the concepts that we will be describing and discussing later on.

If you have been programming in other languages, you might have learned words like methods, functions and procedures. These are all named just "functions" in C++. A C++ program in its simplest form consist only of one function, which is called main. This is a pre-defined function name, and its body is enclosed in braces {}. The main function needs to exist so that your system (your run-time enviroment) will know where to start the execution of your program. If it didn't exist it would be like not knowing where to start reading a book. In order for your program to make sense, it needs a starting location – the main function.

When writing C++ code, you will be using some sort of text editor. If you are programming in a Windows enviroment, you could use a simple text editor like Notepad, Textpad or Notepad2. If you're in a linux enviroment you could use i.e. Notepad++, Pico or Nano. It really doesn't matter which editor you choose to use, as long as you give your source files the extension *.cpp. I.e. your first program could be named:

myFirstProgram.cpp

Let's say this file contains some code that you've written using Notepad. In order to make this file an actual program, we need to translate it into native machine code, a binary code consisting of only ones and zeros. Fortunately we don't do this manually. We have a program to do it for us – the compiler.

There are many C++ compilers out there, which perform pretty much the same (although they may vary slightly). It all boils down to this: You will have to make choice. Which editor will you be using? Which compiler will you be using? Tough questions? Well, don't worry. We will provide for you a complete and easy solution to these questions. This solution applies best to the Windows OS, because binaries only are availible to Windows systems. You can however compile the source code for your desired system. Well, anyway, the answer that we like, is Dev-C++ from Bloodshed. Dev-C++ is what we call an "IDE" (Integrated Development Enviroment). An IDE combines the editor, compiler and other useful tools in the same software package. There are of course alternatives, but Dev-C++ is under GNU General Public License which means it's free and open source (publicly availible source code), and it's also a very neat IDE.

The Dev-C++ workspace – a simple and nice GUI
The Dev-C++ workspace – a simple and nice GUI

Note: There might be other IDE alternatives that are better if you're an OS X or Linux user. If you want more information about this, just google it. I.e. "c++ IDE for linux", or simply post your question at our site.

For downloads and more information, please check out:
http://sourceforge.net/projects/dev-cpp/

After installing the IDE, we are ready to move on to our next section.

Writing your first program

Start up your IDE software, and create a new source file (a clean document). In Dev-C++ you can hit CTRL + N. This is where we'll type our code. So, let's get started.

Our program will be using commands for outputting and inputting information in a console window. To enable this functionality, we must include a library named iostream. Then we have to choose namespace to use, so the compiler will know what names are connected to our imported functionality. You don't need to fully understand at this point. The numbers to the left are line numbers.

1   #include <iostream>
2 using namespace std;

Next we have our main function, and the starting brace of our main function. As you can see the main function should return an integer value. When we return the value 0 (later in the code), our program will be terminated. This is considered good style, but it is not required by all compilers. Some compilers will allow your main method to return nothing thus writing void main( ), and some compilers doesn't even require a return statement, even if the function should return an integer. Well, anyway, we will use the following style, because it is good style.

3    int main( )
4 {

We are now inside the main function. The code that we write here will be executed line by line. So, let's declare a variable of type int, that we will name yourLuckyNumber. Btw: int is the C++ type for whole numbers; integers. Then we will use some of our imported functionality: cout (console output) and cin (console input). This is used for outputting and indputting information in the console window. Note that cout and cin used different operators (<< and >>). You will learn about operators later. Note: endl ends the current outputted line.

5        int yourLuckyNumber;

6 cout << "Please enter your lucky number, and hit enter: ";
7 cin >> yourLuckyNumber;
8 cout << endl;

Now that we have read an integer from the user, and stored this value in our variable, we can analyze this number so we can output appropriate information.

9        /* Determine whether your number is positive,    
10 negative or zero */

11 cout << "Your lucky number is ";

12 if (yourLuckyNumber == 0)
13 {
14 cout << "zero";
15 }
16 else if (yourLuckyNumber < 0)
17 {
18 cout << "negative";
19 }
20 else if (yourLuckyNumber > 0)
21 {
22 cout << "positive";
23 }

Line 9 and 10 are comments. By enclosing text within /* and */ you can provide information for yourself and the person that is reading your code. Comments will be skipped by the compiler and can be very useful when documenting the different parts of your program.

Now we will use an operator which is called modulo (in C++ this is represented by the percent symbol, %). The modulo function finds the remainder of division of one number by another. Given two numbers, a (the dividend) and n (the divisor), a % n is the remainder, on division of a by n. In example, the expression "7 % 3" would evaluate to 1, while "9 % 3" would evaluate to 0.

This function can be used to determine whether an integer is odd or even. If we have an integer, n, then the following expression will help us determine whether n is odd or even "n % 2". If the remainder is 0, then it is even (or zero), and if it's 1 that means our integer is an odd number.

24       cout << ", and it is also an ";

25 //Determine whether your number is an odd or even number
26 if (yourLuckyNumber % 2 == 0)
27 {
28 cout << "even number.";
29 }
30 else if (yourLuckyNumber % 2 != 0)
31 {
32 cout << "odd number.";
33 }

34 cout << endl;
35 cout << "That is all =)";
36 cout << endl;
37 system ("PAUSE");
38 return 0;
39 }

Notice line 25. Here we use a different style for our comment. In stead of enclosing some text within /* and */, we use // to make the rest of the line a comment, but only this line. If our comment uses more space than one line, we could put // in the beginning of each line, or we could enclose it with /* and */ as previously discussed.

Line 37 makes the console perform a pause. If we omit this line then our console window would open up, run, and then close again, giving us very little time to read the output of our program. Line 38 and 39 includes the return statement for the main function, and the closing brace for the main funciton.

You now have a complete C++ program which is ready to be compiled. If you are using Dev-C++ you can hit F9 (compile and run).

Here is the program running under Windows XP:
A sample run of our program
A sample run of our program (click for full size)

0 comments: