Professional Documents
Culture Documents
Requirements
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:
This will let us use certain commands without having to type out their
full name. Now we will type the main function.
int main()
{
}
return 0;
#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.
-I"C:\Borland\BCC55\include"
-L"C:\Borland\BCC55\lib"
Comments
int main()
{
cout << "Hello World\n"; // Print Hello World on the screen
return 0; // Return 0 to the OS
}
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;
Name Stores
bool true or false
char Characters
int Numbers
float Numbers
double Numbers
You can declare 2 variables of the same type on one line by separating
them with a comma.
int i, j;
Using variables
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;
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");
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 <<.
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;
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?
const PI = 3.14;
#define PI 3.14
Lesson 3 - Decisions
if statement
int age;
cout << "Enter your age: ";
cin >> age;
if (age == 18)
cout << "\nYou are 18 years old";
== 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";
}
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.
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";
}
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";
}
Lesson 5 - Pointers
What is a pointer?
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;
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;
void *up;
#include<malloc>
...
void *up;
up = malloc(100);
free(up);
Lesson 6 - Arrays
What is 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;
arr
012
0524
1379
2618
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;
int arr[3][3];
for (int x=0; x<3; x++)
for (int y=0; y<3; y++)
arr[x][y] = 0;
Lesson 7 - Functions
What is a 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";
}
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();
}
void main()
{
g = 3;
}
Parameters
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 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();
}
Lesson 8 - Structures
What is a structure?
#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;
Lesson 9 - Reading and writing text and data 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);
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;
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.
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.
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
class Student
{
private:
int stunum;
public:
void setstunum(int sn);
int getstunum();
};
int Student::getstunum()
{
return stunum;
}
Classes vs objects
Student stu;
class Student
{
private:
int stunum;
public:
Student();
~Student();
};
Student::Student()
{
cout << "Object has been created" << endl;
}
Student::~Student()
{
cout << "Object has been destroyed" << endl;
}
#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();
};
int Student::getstunum()
{
return stunum;
}
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;
}