Sunday, 19 August 2012

C++ Programming Tutorial Lesson #10 - Classes


Creating a class

The class keyword is used when creating a class followed by the class name. All other parts of the class are put inside curly brackets. The last curly bracket must be followed by a semi-colon. Here is an example of how to create a class called Student.
class Student
{
};
A class can have private members which other parts of the program can't access and public members which can be accessed from outside the class. The private and public keywords are used for this.
class Student
{
private:
   char name[50];
public:
   int stunum;
};

Methods

Methods are functions that belong to an object. You must declare a method between the curly brackets of the class declaration and the full method with its code outside the class. Let's create methods for setting and getting the student number.
class Student
{
private:
   int stunum;
public:
   void setstunum(int sn);
   int getstunum();
};

void Student::setstunum(int sn)
{
   stunum = sn;
}

int Student::getstunum()
{
   return stunum;
}

Classes vs objects

An instance of a class called an object must be created before you can use it. This is because the class is like the plans for a house and the object is the actual house that has been built. Here is how you instantiate an object called stu of the Student class.
Student stu;

Constructors and destructors

A constructor is a method that runs when an object is instantiated. You can use a constructor to set the initial values of an object. A destructor runs when the object is destroyed. The constructor and destructor have the same names as the class and no return value but the destructor has a tilde in front of its name. Here is an example of the constructor and destructor for the Student class.
class Student
{
private:
   int stunum;
public:
   Student();
   ~Student();
};

Student::Student()
{
   cout << "Object has been created" << endl;
}

Student::~Student()
{
   cout << "Object has been destroyed" << endl;
}
A constructor can take parameters for when an object is instantiated and it can have default values for parameters. Here is an example of how to create a Student with the name John whose student number is 10000 and a Student called Mary who is given the default student number of 12345. It is a full program that includes methods for getting and setting all values.
#include<iostream>

class Student
{
private:
   char name[50];
   int stunum;
public:
   Student(char *n,int sn=12345);
   void setstunum(int sn);
   int getstunum();
   void Student::setname(char *n);
   char *Student::getname();
   ~Student();
};

Student::Student(char *n,int sn)
{
   strcpy(name,n);
   stunum = sn;
}

void Student::setstunum(int sn)
{
   stunum = sn;
}

int Student::getstunum()
{
   return stunum;
}

void Student::setname(char *n)
{
   strcpy(name,n);
}

char *Student::getname()
{
   return name;
}

Student::~Student()
{
   cout << "Object has been destroyed" << endl;
}

int main()
{
   Student stu1("John",10000);
   Student stu2("Mary");
   stu1.setstunum(50000);
   cout << stu1.getstunum() << endl;
   cout << stu1.getname() << endl;
   cout << stu2.getstunum() << endl;
   cout << stu2.getname() << endl;
   return 0;
}

C++ Programming Tutorial Lesson #9 - Reading and writing text and data files


Writing text files

A text file is a file that stores words and sentences in plain text. You must include the fstream.h header file before you can use files. You must then create a ofstream object which will let you open a file and output data to it. When creating the object you must put the name of the file you want to open in brackets. If the file does not exist it will be created and if it already exists it will be cleared.
ofstream f("test.txt");
You write to a file in a similar way as you write to the screen. All you have to do is replace cout with the name of the ofstream object.
f << "Hello";
Use the close method of the ofstream object to close the file when you are finished working with it. If you don't close a file then some data may not be written to it.
f.close();

Appending to files

Files are cleared by default when you open them. If you want to add things to an existing file then you must open it for appending by using ios::app when opening the file.
ofstream f("test.txt",ios::app);

Reading text files

You must declare an ifstream object instead of an ofstream when reading from files.
ifstream f("test.txt");
You need to declare a character array to store the data read when reading from a file. The character array can be any size as long as it is big enough to store what you are reading in.
char s[50];
Reading from a file is similar to using cin. Just replace cin with the name of the ifstream object.
f >> s;

Writing data files

A data file is a file that is usually used to store structures. First we will create a structure called teststruct.
struct teststruct
{
   int a;
   int b;
};
Now let's declare a struct of the teststruct type and set its values.
teststruct ts;
ts.a = 5;
ts.b = 6;
You open a data file in the same way as a text file but you should give the file a .dat extension.
ofstream f("test.dat");
Writing to a data file is a bit more complicated. You must use the write method of the ofstream object. The first parameter of the write method is a pointer to the data structure to be written. The second parameter is the size of the object that you are writing.
f.write((char *)(&ts),sizeof(ts));
Remember to close the file when you are finished writing to it.

Reading data files

To read from a data file we will first create an ifstream object and a structure of the teststructure type.
ifstream f("test.dat");
teststructure ts;
The read method of the ifstream object looks similar to the write method of the ofstream.
f.read((char *)(&ts),sizeof(ts));
You should then test to see if the values were read properly by writing them to the screen.
cout << c.a << endl;
cout << c.b << endl;

C++ Programming Tutorial Lesson #8 - Structures


What is a structure?

A structure is used to group variables together under one name. If you have a student structure for example then you will group the student number and student name together.

How to create and use a structure

The first thing to do when creating a structure is to use the struct keyword followed by the structure name. You need to put curly brackets after that which will contain the things that make up the structure. Always remember to put a semi-colon after the curly brackets. Here is an example of a structure called student.
#include<iostream>

struct student
{
};

int main()
{
   return 0;
}
You must now put the variables that belong to the structure inside the curly brackets. For the following example we will have a student number and student name.
struct student
{
   int num;
   char name[25];
};
The struct is only a definition for what the structure will look like so we have to now declare a structure in memory of the student type. We will call it stu.
int main()
{
   student stu;
   return 0;
}
You must use a dot between the structure name and the sub item to access it. Here is an example of how to set their values and print them out.
student stu;
stu.num = 12345;
strcpy(stu.name,"John Smith");
cout << stu.num << endl;
cout << stu.name << endl;

Pointers to structures

When you are using a pointer to a structure then you must use a -> instead of a dot. Here is an example of how to set the student number using a pointer to the student structure.
student stu;
student *sp = &stu;
sp->num = 10000;

C++ Programming Tutorial Lesson #7 - Functions


What is a function?

A function is a sub-program that your program can call to perform a task. When you have a piece of code that is repeated often you should put it into a function and call that function instead of repeating the code.

Creating your own function

You declare a function in a similar way as you create the main function. You first put void then the function name and some brackets. The function code goes between curly brackets after that. Here is a function that prints Hello.
void PrintHello()
{
   cout << "Hello\n";
}

Calling your function

Once you have created the function you must call it from the main program. Here is an example of how to call the PrintHello function from above.
void PrintHello()
{
   cout << "Hello\n";
}

void main()
{
   PrintHello();
}

Local and global variables

If you declare a variable inside a function then it is only accessible by that function and is called a local variable. If you declare a variable outside of all functions then it is accessible by any function and is called a global variable.
int g; // Global variable

void MyFunction()
{
   int l; // Local variable
   l = 5;
   g = 7;
}

void main()
{
   g = 3;
}

Parameters

You must use parameters to pass values to a function. Parameters go between the brackets that come after a function. You must choose the datatype of all parameters. We will now create a function that receives a number as a parameter and then prints it.
void PrintNumber(int n)
{
   cout << n;
}

void main()
{
   PrintNumber(5);
}
If you want to pass more than one value then you must separate parameters with a comma.
void PrintNumber(int n, int m)
{
   cout << n << m;
}

void main()
{
   PrintNumber(5, 6);
}
You can either pass a parameter by reference or by value. The default is by value which means that a copy of the variable is made for that function. If you use a * in front of the parameter then you will be passing only a pointer to that variable instead of making another copy of it.
void PrintNumber(int *n)
{
   cout << *n;
}

void main()
{
   int i = 5;
   PrintNumber(&i);
}

Return values

A function can return a value that you can store in a variable. We have been using void in the place of the return variable until now. Here is an example of how to return the number 5 from a function and store it in a variable.
int GetNumber()
{
   return 5;
}

void main()
{
   int i = GetNumber();
}

C++ Programming Tutorial Lesson #6 - Arrays


What is an array?

An array is a group of variables that uses one name instead of many. To access each of the individual variables you use a number.

How to use an array

To declare an array put square brackets after the name of the array. These square brackets must have the number of variables or elements inside them. Here is an example of how to declare an array of integers which has 3 elements
int arr[3];
You can set the values of an array by using the number of the element you want to set in the square brackets behind it. Array elements start from 0 and not 1.
int arr[3];
arr[0] = 5;
arr[1] = 7;
arr[2] = 3;
Here is a table that shows you what the array looks like.
arr
05
17
23

2D arrays

A 2D array is an array that has both rows and columns. You must use 2 sets of square brackets when declaring a 2D array and when using it.
int arr[3][3];
arr[0][0] = 5;
Here is a table that shows you what a 2D array looks like.
arr
012
0524
1379
2618

Using arrays with loops

Arrays appear to be nothing more than normal variables until you use them with loops. You can initialize all the elements of an array to 0 using a loop instead of setting them each individually.
int arr[3];
for (int x=0; x<3; x++)
   arr[x] = 0;
When you do this with a 2D array you need to use 2 loops.
int arr[3][3];
for (int x=0; x<3; x++)
   for (int y=0; y<3; y++)
      arr[x][y] = 0;

C++ Programming Tutorial Lesson #5 - Pointers


What is a pointer?

A pointer is a variable that holds a memory address. It is called a pointer because it points to the value at the address that it stores.

Using pointers

If you want to declare a pointer variable you must first choose what data type it will point to such as an int or a char. You then declare it as if you were declaring a variable in the normal way and then put a * in front of its name to show that it is a pointer. Here is an example of how to declare a pointer to an integer.
int *pi;
You can store the address of another variable in a pointer using the & operator. Here is an example of how to store the address of variable called i in the pointer called pi.
int i;
int *pi;
pi = &i;
You must dereference a pointer to get the value at the memory location that the pointer points to. You use the * operator to dereference a pointer. Here is an example of how we first set the value of i to 5 and then set its value to 7 by dereferencing the pointer.
int i = 5;
int *pi;
pi = &i;
*pi = 7;
cout << i;

new and delete

The new operator is used to allocate memory that is the size of a certain data type. It returns a pointer to the address of the newly allocated memory. Here is an example of how to allocate memory for an integer and then set its value to 5.
int *pi;
pi = new int;
*pi = 5;
The delete operator deallocates memory. You need to deallocate the memory for all the memory that you have previously allocated before exiting the program or else you will have memory leaks.
int *pi;
pi = new int;
*pi = 5;
delete pi;

Typed and untyped pointers

We have been using typed pointers so far because they point to a specific data type. An untyped pointer can point to anything. You declare an untyped pointer as the data type void.
void *up;

malloc and free

The malloc command allocates a certain number of bytes and returns a pointer to the first byte. You must use the free command to deallocate the memory that was allocated with malloc. To be able to use malloc and free you must include the malloc header file. Here is an example that allocates 100 bytes of memory and stores the address of it in the pointer called up and then deallocates the memory.
#include<malloc>
...
void *up;
up = malloc(100);
free(up);

C++ Programming Tutorial Lesson #4 - Loops


A loop lets you repeat lines of code as many times as you need instead of having to type out the code a whole lot of times.

For Loop

The for loop is used to repeat code a certain number of times between 2 numbers. You have to use a loop variable to go through each loop. The first part of a for loop initializes the loop variable to the number from which the loop starts. The second part is the condition that the loop must meet to exit the loop. The third part is used to increment the value of the loop variable. Here is an example of how to print the word Hello 10 times.
int x;
for (x = 1; x <= 10; x++)
   cout << "Hello\n";
The x++ part is something you haven't seen yet. Adding ++ to the front or back of a variable will increment it by 1. -- is used to decrement by 1. Putting the ++ before the variable increments it before the condition of the loop is tested and putting it after increments it after the loop condition is tested.
If you want to use more than one line of code in a loop then you must use curly brackets just like with an if statement.
int x;
for (x = 1; x <= 10; x++)
{
   cout << "Hello\n";
   cout << "There\n";
}

While Loop

The while loop repeats code until a condition is met. You don't have to use a loop variable but if you do then you need to initialize it before running the loop. You also need to increment the loop variable inside the loop.
int x = 1;
while (x <= 10)
{
   cout << "Hello\n";
   x = x + 1;
}

Do While Loop

The do while loop is like the while loop except that the condition is tested at the bottom of the loop.
int x = 1;
do
{
   cout << "Hello\n";
   x = x + 1;
}
while (x <= 10);

Break

The break command can be used to exit a loop at any time. Here is one of the above examples that will only print Hello once and then break out of the loop.
int x;
for (x = 1; x <= 10; x++)
{
   cout << "Hello\n";
   break;
}

Continue

The continue command lets you start the next iteration of the loop. The following example will not print Hello because the continue command goes back to the beginning of the loop each time.
int x;
for (x = 1; x <= 10; x++)
{
   continue;
   cout << "Hello\n";
}

C++ Programming Tutorial Lesson #3 - Decisions


if statement

The if statement is used to test the values of variables and do something depending on the result. For example you can check if a value that the user has entered is equal to a certain value.
int age;
cout << "Enter your age: ";
cin >> age;
if (age == 18)
   cout << "\nYou are 18 years old";
In the above example you will see that we used a == instead of a = because == is used for testing equality and = is used to assign a value to a variable. If the age entered by the user equals 18 then it prints "You are 18 years old" on the screen. Here are the operators that can be used in an if statement.
==Equal
!=Not equal
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to
If you want to put more than one command in an if statement then you must surround them with curly brackets.
int age;
cout << "Enter your age: ";
cin >> age;
if (age == 18)
{
   cout << "\nYou are ";
   cout << "\n18 years old";
}
Nested if statements are if statements that have if statements inside them.
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "\nEnter second number: ";
cin >> num2;
if (num1 == 1)
   if (num2 == 2)
      cout << "\nYou entered the right values";
The if statement actually tests the condition and then converts it to a true or a false. If the age that was entered equals 18 in our example then it converts it to true and if it is not 18 then it converts it to false. If the condition is true it runs the code immediately after the if statement. The else statement is an optional part of an if statement and the code immediately after it is run if the condition is false.
int age;
cout << "Enter your age: ";
cin >> age;
if (age >= 18)
   cout << "\nYou are an adult";
else
   cout << "\nYou are a child";
You can test 2 conditions at once using the && operator. The || operator tests if one or both of the conditions is true . The ! operator changes the condition to false if it is true and true if it is false.
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "\nEnter second number: ";
cin >> num2;
if (num1 == 1 && num2 == 2)
   cout << "\nYou entered the right values";
if (num1 == 1 || num2 == 2)
   cout << "\nOne of the values is right";
if (!(num1 == 1))
   cout << "\nYou entered the wrong value";

switch statement

The switch statement can be used to test for multiple values for the same variable. For each possible value you can run some code and you must put a break statement after each one except the last. There is a default option for when none of the values are met.
int age;
cout << "What is your age: ";
cin >> age;
switch (age)
{
   case 1: cout << "You are 1 year old";
           break;
   case 2: cout << "You are 2 years old";
           break;
   case 3: cout << "You are 3 years old";
           break;
   default: cout << "You are older than 3 years";
}

C++ Programming Tutorial Lesson #2 - Variables and Constants


What are variables?

A variable is a space in memory where a program stores data. Variables can store numbers and letters among other things.

Declaring variables

Before you can use a variable you must declare it. When you declare a variable you choose its data type and give it a name. Here is an example of how to declare a variable of the data type integer with the name i.
int i;
Here is a table of the basic data types that C++ supports.
NameStores
booltrue or false
charCharacters
intNumbers
floatNumbers
doubleNumbers
You can declare 2 variables of the same type on one line by separating them with a comma.
int i, j;

Using variables

You set the value of a variable using a =. Here is an example of how to set the value of an int called i to 5.
int i;
i = 5;
You can set the value of a variable at the same time as you declare it. This is called initialization.
int i = 5;
A char is a letter, number or any special character. You must put char values inside single quotes.
char c = 'a';
A bool variable can only store either true or false.
bool b = true;
bool c = false;
A variable can also be signed or unsigned. Signed means that it can have negative numbers and unsigned means it can't but unsigned gives a variable a greater positive range. You simply put the words signed or unsigned in front of a variable declaration to use them.
unsigned int i;
Putting short or long in front of a variable gives it a smaller or bigger range respectively.
short int i;
Using signed, unsigned, short and long without a variable type will use int by default.
signed s;
unsigned u;
short sh;
long l;
A string is a type of variable that can store words and sentences. There are 2 kinds of strings. The first kind is a string pointer. You declare it as a *char. The * means that it points to the first char of the string.
char *s;
s = "Hello";
The second kind is an array of characters which you must give a size when you declare it. You have to use the strcpy command to put values in it. You must also include the string header file to be able to use the strcpy command.
#include<string>
...
char t[10];
strcpy(t,"Hello");

User input and output with variables

The cout command can be used to print the value of a variable on the screen. If you want to print text and variable values at the same time then you must separate them with a <<.
int age = 18;
cout << "Your age is " << age;
The cin command is used for reading in values that are entered by the user. When you read a value you must store it inside a variable. Here is an example of how to read an int into a variable.
int age;
cout << "Enter your age: ";
cin >> age;

Calculations with variables

You can add, subtract, multiply and divide when working with variables. When you do this you must store the result in a variable. You can also use variables in calculations including the variable that is going to store the result.
int i, j, k, l;
i = 1 + 2;
j = 5 - 3;
k = 10 * 2;
l = 100 / 5;
i = j + 5;
i = i - 2;

What are constants?

A constant is a variable whose value can't change. Constants are used to give a meaningful name to a value such as the name PI for 3.14. The value of a constant must always be set when it is declared. There are 2 types of constants. The first uses the word const in front of the declaration.
const PI = 3.14;
The other type of constant uses #define to create a constant.
#define PI 3.14

C++ Programming Tutorial Lesson #1 - First Program


Requirements

Before we start programming in C++ we need a compiler. We will be using a command line compiler for this tutorial. I will be using Borland C++ Compiler 5.5 but you can use any other ANSI/ISO compliant compiler such as gcc.

Hello World Program

Our first C++ program will print the message "Hello World" on the screen. Open a text editor and start by typing the following line:
#include<iostream>
The above line includes the header file called iostream which will allow us to use the command to print words on the screen. Next you must type:
using namespace std;
This will let us use certain commands without having to type out their full name. Now we will type the main function.
int main()
{
}
The main function is where a program always starts. Every program must have a main function. The word int in front of main is to say what the return value is. The curly brackets belong to the main function and show where it begins and where it ends. Now we will type the command that prints "Hello World" on the screen between the curly brackets.
cout << "Hello World\n";
The cout command is used to print things on the screen. The << means that the text must be output. The words that you want printed must be surrounded by quotes. The \n means that the cursor must go the beginning of the next line. Lastly we must return 0 to the operating system to tell it that there were no errors while running the program.
return 0;
The full program should look like this:
#include<iostream>
using namespace std;

int main()
{
   cout << "Hello World\n";
   return 0;
}
Save the file as hello.cpp. You now need to compile the program. You need to open a command prompt and type the command name of your C++ compiler and the name of the C++ file you have just created. Here is an example of how to do it with Borland C++:
bcc32 hello.cpp
If you are given error messages then you have made mistakes which means you should go through this lesson again and fix them. If you don't get any errors then you should end up with an executable file which in my case is called hello.exe. Enter hello to run the program and you should see "Hello World" printed on the screen. Congratulations! You have just made your first C++ program.
Important note for Borland C++ users
Once you have downloaded and installed Borland C++ you need to add "C:\Borland\BCC55\Bin" to your path. If you are using Windows NT/2000/XP then you need to open the control panel and then double click on "system". Click on the "Advanced" tab and then click "Environment Variables". Select the item called "Path" and then click "Edit". Add ";C:\Borland\BCC55\Bin" to "Variable value" in the dialog box that appears and then click Ok and close everything. You will also have to create a text file called "bcc32.cfg" in "C:\Borland\BCC55\Bin" and save the following lines of text in it:
-I"C:\Borland\BCC55\include"
-L"C:\Borland\BCC55\lib"

Comments

Comments explain what a program does and are ignored by the compiler. A single line comment goes after a // and a multiple line comment goes between a /* and a */. Here is an example of how to comment the program we have just made:
/* This program will print the words
Hello World on the screen. */

#include<iostream>
using namespace std;

int main()
{
   cout << "Hello World\n"; // Print Hello World on the screen
   return 0; // Return 0 to the OS
}