Cơ bản về C++ – Basic C++ Lessons

Cơ bản về C++ – Basic C++ Lessons
Why C++?
C++ is a simple yet powerful Object Oriented programming language. It has almost all the same uses as C, but brings a few new features to the table, along with simpler code. One of the new features is a data type called class, which is used to create objects. Objects will allow you to write your code in a more organized fashion, instead of having data scattered about. This makes it much easier for the different functions throughout your program to access the data they need in order to get the job done. This way the amount of code you have to write is reduced significantly, thus making your program easier to maintain.Where to start
First thing you will need is a compiler. A compiler basically takes the code you write and translates it into a form the computer will understand so that it can be executed. I used Dev-C++ for the examples you will find throughout this site, although the code should work with most compilers. Dev-C++ can be found on Bloodshed’s site.Lets Begin
Now that you have your compiler, lets move on to actually learning how to code C++. If you are using Dev-C++, the first thing you are going to want to do once you open it is select “File” > “New” > “Project. Then select “Console Application” and name your project. Once finished you will be presented with a small program, simply erase this so we can begin! Our first program will simply send “Hello World!” to the screen, here is the code://My first program

#include

using namespace std;

int main(){

cout << “Hello World!\n”;

system(“Pause”);

}

Now lets break this down. The first line “//My first program” is a comment, the compiler will ignore this line completely. To add comments to your program, simply begin the line with “//” and anything after that will be ignored.

The first line of actuall code tells the compiler that we want to include “iostream” in our program. iostream is part of the standard library, all C++ compilers will understand any command included in any part of the standard library. iostream contains the basic I/O functions used to write to the screen and recieve input from the user.

The next line “using namespace std;” defines what namespace we will be using, in this case std. A namespace is basically a list of variable and function names, in order to not get standard library names mixed with others, the standard library creates the namespace std, so any time you want to use a command from the standard library you must include this line. The semicolon at the end of the line is needed for almost every line in C++, this tells the compiler that it has reached the end of that line.

“int main(){” this is a function decleration. A function is a block of code which begins and ends with a pair of curly brackets ” { } “. This way we have a way of referencing this block of code in case if we want the program to run the same code multipule times. Functions also help keep the code looking clean. “int” is the data type the function returns, we will discuss data types later. “main” is the name of this function, every C++ program must have a main() function, this is where the program will begin to execute. If you want to pass a variable to a function, you would place the type of variable and specify a name for it between the parenthesis, for example “int myFunction( int number)”. The curly braket shows where the function begins.

“cout << “Hello World!\n”;” This line displays the text “Hello World!” on the screen. cout takes the text using “<

“system(“Pause”);” system() is used to send commands to the operating system, in this case we are sending “pause” which is a DOS command which pauses the screen until the user presses any key. I included this because once the program runs out of code to execute, it will close the window and you will not get a chance to see the results.

Ok now lets see it in action, type the code into Dev-C++, do not copy and paste it. You can copy and paste if you want, it will work just fine, but it will help you memorize the code quicker if you type it yourself. Once done, save it and press the compile button, once it finished press the run button. You should be presented with a DOS prompt which will give you this output:

Hello World!
Press any key to continue…

Too easy isn’t it? Lets move on to data types.
Data types
So far you’ve seen how to display whatever you put into your program, now lets see how to get input from the user. Before doing this we need somewhere to store the data the user gives us, this is where the different data types come in. Here is a list of the basics data types:

int: used to store integers (whole numbers, no decimals/fractions)
long: used to store larger integers
float: used to store numbers with multiple decimal places
double: also used for numbers with multiple decimal places, but has double the space in memory as a float (more decimal places)
char: used to store a single character

Ok now lets see these in action:

#include

using namespace std;

int a;

int main(){

int b;
int c;

cout << “Enter a number: “; cin >> a;

cout << “Enter a second number: “; cin >> b;

c = a+b;

cout << “The sum is: ” << c << “\n”;

system(“pause”);

}

Here I declared three integers, a, b, and c. Notice how “a” is outside of main()? In this case, a would be known as a global variable, all functions can access it freely, but since b and c were declared inside of main() it is only accessible to main().

The next new line would be “cin << a+b;”. Here we see the insertion operator again, except this time its pointing in the other direction. Since cin is the command for input, we want to “funnel” the data from the function to the variable.

After collecting the information from the user we use it to give c a value. “c = a+b;” give c the value of the sum of a and b, you can also use – for subtraction, * for multiplication, and / for division.

Finally we display the value of c, notice how there are two insertion operators in the final output? This allows us to display text and variables in one line instead of having to write “cout” several times. Notice how text is written in between quotes and variables are without quotes. If you wanted to assign a variable a number you would not use quotes either ( int a = 10; ).

Arrays
In the last lesson we saw how to create simple variables and store user input in them. Now we will look into arrays. An array is simply a list of variables of the same type. Lets say your program required you to keep track of 100 integers, in which case you would have to create 100 integers by typing up each one, one by one… Needless to say that would take quite a while, but with arrays you can cut the typing down to one single line! Lets see how it works:

#include

using namespace std;

int main(){

int myArray[3];

cout << “Enter a number: “; cin >> myArray[0];

cout << “Enter a second number: “; cin >> myArray[1];

myArray[2] = myArray[0]+myArray[1];

cout << “The sum is: ” << myArray[2];

system(“pause”);

}

Here we have the same sample program from the previous lesson, except I replaced the three integers with a single array made up of three integers. “int myArray[3];” creates an array of three integers. Each integer inside this array will have a corresponding number, starting at 0. So in this case the three integers are myArray[0], myArray[1], and myArray[2]. Since 0 counts, there is not myArray[3]! Everything else is exactly the same.

You can also use arrays to store a string of text by creating an array of characters. Here you would make the array the max size of characters you want plus one, since strings must end the null character (null mean nothing, not 0, just nothing). We will look more into strings in a latter lesson though.
Two Dimensional Arrays
2D arrays work just like normal arrays except they have two numbers per variable. In order to declare one you would add an extra pair of brackets (int my2dArray[3][3]). Here is a graphical representation of a 2D array:

XXX
XXX
XXX

These will come in handy when you are programming graphics and animations, lets see an example program:

#include

using namespace std;

int main(){

int myArray[10][10];
for (int i = 0; i

for (int t = 0; t

myArray[i][t] = i+t; //This will give each element a value

}

}

for (int i = 0; i

for (int t = 0; t

cout << myArray[i][t];

}

}

system(“pause”);

}

Ignore the for loops for now, we will look into those in the loops lesson. This program simply assigns a value to each element in myArray and then displays each one. As you can see there is not much difference between using normal arrays and 2d arrays.

If-Then-Else
Now we will look into how to get our programs to compare values. A conditional statement checks to see if the conditions you are looking for are met or not, if they are they will execute a certain block of code, if not they will keep on. Here is an example:

#include

using namespace std;

int main(){

int a;
int b;

cout << “Enter a value for a: “; cin >> a;

cout << “Enter a value for b: “; cin >> b;

if (a > b){

cout << a << “Is greater than” << b;

} else if(a < b){

cout << a << “Is less than” << b;

} else {

cout << a << “Is equal to” << b;

}

}

Here we see what is known as an if-then-else statemnt. I basically reads “If a is greater than b execute this code” if it is not greater it will move on, if it is true it will execute what ever you place in between its curly brackets and continue ignoring any line that begins with else after it. If it is false, the program will check the next condition “else if(a < b){” which basically reads “If the condition above is false and a is less than b execute this code”. Finally, if that one proves false as well the program will go to the final “else” which has no conditions so will always be executed if the above conditions were false. Here are a list of the condition you can chck for:

== : equality, must use two equal signs
< : less than > : greater than
= : greater than or equal to
!= : not equal

You can also check for more than one condition with a single if by using && (for and) and || (for or). For example:

if( a == 1 && b != 2) // will return true if a has a value of 1 and b does not have a value of 2

if( a == 1 || b != 2) // will return true if a has a value of 1 or if b does not equal 2

Switch Case
The switch case works much like a lot of if-then-else statements put together. It takes one value and compares it against many others. Here is an examle:

#include

using namespace std;

int main(){

int a;

cout << “What time of day is it?\n”;
cout << “1) Morning\n”;
cout << “2) Afternoon\n”;
cout << “3) Evening\n”;
cout << “Enter a choice: “; cin >> a;

switch (a){

case 1:
cout << “Good Morning!”;
break;
case 2:
cout << “Good Afternoon!”;
break;
case 3:
cout << “Good Evening!”;
break;

default:
cout << “Not a valid entry…”;
break;

}

}

Notice how after each case, there is a colon not a semicolon. The last command in each case must be “break;” if not it will continue to execute any code following it. “break;” can be used to break out of any conditional statement or loop. “default” is included incase the user eneters an invalid entry, when ever the variable doesnt match any case, the default block is executed.

Strings
A string is an array of characters. In order to get text from a user you must use a string. Strings work a bit different from other arrays though, here we will look into the different funcitons used for strings. Here is an example:

#include
#include
#include

using namespace std;

int main(){

char myArray[50];

cout << “Whats the password? “;

cin.getline( myArray, 50, ‘\n’);

if( !strcmp( myArray, “cheesecake”)){

strcat( myArray, ” is correct! Access granted!\n”);

} else {

strcpy( myArray, “Invalid password!\n”);

}

cout << myArray;

system(“pause”);

}

Here we begin by declaring a string of 50 characters. The first line with a new function would be “cin.getline( myArray, 50, ‘\n’);”, the first parameter getline() takes is the string you want to store the data in, next is the max amount of characters allowed, and finally what you want the string to be terminated with.

“if( !strcmp( myArray, “cheesecake”)){” will check if myArray is equal to cheesecake. Notice how I used the Not operator here, this is because strcmp returns false if the condition is met. Also remember strcmp() is case sensitive!

“strcat( myArray, ” is correct! Access granted!\n”);” This will add ” is correct! Access granted!\n” to the end of myArray, you can also place another string in place of the text in order to join two strings.

“strcpy( myArray, “Invalid password!\n”);” This will replace myArray with “Invalid password!\n”. Whatever was in myArray will be wiped out and replaced by the text.

While Loop
Loops are used to loop back and execute the same block of code over and over again until a certain condition is met. Heres an example using the while loop:

#include

using namespace std;

int main(){

int a;

cout << “How many times do you want the loop to run? “; cin >> a;

while (a){
cout << a << “\n”;
–a;
}

return 0;

}

This code takes a value from the user and runs a while loop that many times. The conditions used for the while loop are the same as the if-then-else statements, same goes for every loop. Here since I only put “a” the program will read “While a is true execute this block” and as long as a is a positive integer it is considered to be ‘true’.
For Loop
The for loop works a little bit differently. Instead of taking just one parameter, it takes three. The first is the variable you want to use, you can either use an existing one, or declare one within the for loop. The second parameter is the condition, and the third is used to change the value of the variable chosen in the first parameter. Lets look at the code from the Arrays lesson:

#include

using namespace std;

int main(){

int myArray[10][10];
for (int i = 0; i

for (int t = 0; t

myArray[i][t] = i+t; //This will give each element a value

}

}

for (int i = 0; i

for (int t = 0; t

cout << myArray[i][t];

}

}

system(“pause”);

}

Here the first for loop defines i as an integer with a value of 0. Since the array is 10×10 and 0 counts when counting the elements of an array, we will run the loop until i is equal or greater than 9. “++i” means “add 1 to i”, it can be used with any numeric data type. Since the array is two dimensional we will need a second for loop to get the second index number. This is setup the exact same way, except I used a t instead of an i. So now every time the first for loop runs, the second will run 10 times, and then return to the first until the first has been run 10 times thus covering every element in the array.

Functions
Functions are used to define a block of code, unlike the loops we discussed earlier, functions can be called from any place in your program so that you do not have to repeat the same code over and over again. Here is a basic function at work:

#include

using namespace std;

int addNumbers( int a, int b){

return a+b;

}

int main(){

int a;
int b;

cout << “Enter a number: “; cin >> a;

cout << “Enter an other number: “; cin >> b;

cout << “Sum of the two numbers is: ” << addNumbers( a, b) << “\n”;

system(“pause”);

return 0;

}

Here we create a function called addNumbers, which returns an integer. main() collects the data from the user and then sends it to addNumbers(), notice how I declared the integers in both main() and addNumbers. This is because the ones in main() are local variables which cannot be touched by other functions. The parameters for addNumbers() does not have to be the same as the variables containing the values being sent to addNumbers(). Once addNumbers() is called, it takes the values given to it by main() and returns the sum of them to the function that called it, which in this case is main(). Also notice how addNumbers() goes before main(). If you flip them around it will error out. If a function is being called by a function that apears before it in your source file, it must be declared at before it is called. Here is an example of this:

#include

using namespace std;

int addNumbers( int a, int b);

int main(){

int a;
int b;

cout << “Enter a number: “; cin >> a;

cout << “Enter an other number: “; cin >> b;

cout << “Sum of the two numbers is: ” << addNumbers( a, b);

system(“pause”);

return 0;

}

int addNumbers( int a, int b){

return a+b;

}

File I/O
File input and output is extremely simple in C++ compared to C. It works just like reading and writting to standard I/O. In order to use the C++ functions needed to accomplish file I/O you must include the header file . Here is an example:

#include
#include

using namespace std;

int main(){

ofstream outputFile(“file.txt”); //ofstream will create the file if it doesn’t exist, ifstream will not
ifstream inputFile;

char myString[50];

cout << “Enter a string: “;
cin.getline( myString, 50, ‘\n’);

cout << “Writting string to file…\n”;

outputFile << myString;

outputFile.close();

inputFile.open(“file.txt”);

cout << “Reading string from file…\n”;

inputFile.getline(myString, 50, ‘\n’);

cout << myString;

system(“pause”);

return 0;

}

Here are two new data types, ofstream and ifstream. When a program open a file it asigns it a number called a handle in order to keep track of it, this is what is assigned to the ofstream and ifstream type variables every time you open a file. As you see there are two was of opening a file, at the declaration, “ofstream outputFile(“file.txt”);”, and anywhere else by using open(), “inputFile.open(“test.txt”);”.

Output works just like cout, and input works exactly like cin! Notice how I used getline() with inputFile and it worked exactly like it would with cin.

If a file is opened from an ifstream and the file does not exist, it will not create the file. Ofstream will create a non-existant file, but will also wipe out its contents. What if you wanted ifstream to create the file, and ofstream not to? Or have ofstream add to a file rather than delete it? Heres how:

#include
#include

using namespace std;

int main(){

ofstream outputFile(“file.txt”, ios::app); //ofstream will append to file
ifstream inputFile;

char myString[50];

cout << “Enter a string: “;
cin.getline( myString, 50, ‘\n’);

cout << “Writting string to file…\n”;

outputFile << myString;

outputFile.close();

inputFile.open(“file.txt”);

cout << “Reading string from file…\n”;

inputFile.getline(myString, 50, ‘\n’);

cout << myString;

system(“pause”);

return 0;

}

Here we have the same program from before, except we are now adding on to file.txt. Here are other options for files:

ios::app – Apend
ios::trunc – wipe out file
ios::ate – Set position at end of file

Classes
Now for the object oriented programming. Classes are used to create object which can be given different properties and functions just like real life objects making them easier to work with than just a bunch of lose variables. Heres an example:

#include

using namespace std;

class dog{

public:

dog();
~dog();
int getAge();
void setAge(int a);

protected:
int age;

};

dog::dog(){

}

dog::~dog(){

}

int dog::getAge(){

return age;

}

void dog::setAge(int a){

age = a;
}

int main(){

dog myDog;

myDog.setAge(5);

cout << “The dog is ” << myDog.getAge() << ” years old!\n”;

system(“pause”);

return 0;

}

Here I started by creating a class called “dog”. After the class declaration I definded some variables and functions as public and others protected. Public means any function can access them, protected ones can only be called from inside the class. Classes have two special functions called the constructor ( dog() ) and the deconstructor (~dog() ) which are called when an instance of the class is created and destroyed respectively.

“dog myDog” creates an instance of dog called myDog, myDog would be the actuall object modelled after the dog class. In order to run a function inside a class you must use the name of the instance followed by a “.” and the name of the function (myDog.setAge()). The same goes for any public variables you may have declared.

Array of Classes
A class by itself, such as the Dog class from the “Classes” tutorial, is quite useless. To make good use of such a class for video game programming purposes we need to be able to group several of them, this way we can minimize code when it comes to controling several objects at a time. This can be done by creating an Array of the object just like you would with any other data type. I will be splitting this programming up into several files as well, this will help keep things organized once your programs get bigger. Heres the example code:

//Dog.h
#ifndef DOG_H
#define DOG_H 1

class Dog{

public:

Dog();
int getAge();
void setAge(int newValue);

protected:
int age;

};

#endif

This is the header file for the Dog class, it simply holds the prototype for the class, the actual code will be in a seperate file, Dog.cpp. The “#ifndef DOG_H” line is used to make sure Dog isnt declared twice.

//Dog.cpp
#include “Dog.h”

Dog::Dog(){

}

int Dog::getAge(){

return age;

}

void Dog::setAge(int newValue){

age = newValue;

}

Dog.cpp first includes its header file in order to have the prototype for the class, the code here should be familiar from the last lesson.

//main.cpp
#include
#include “Dog.h”

using namespace std;

int main()
{

Dog myDogs[5];

for (int i = 0; imyDogs[i].setAge( i * 2);

for (int i = 0; icout << “Dog number ” << i << ” is ” << myDogs[i].getAge() << ” years old!\n”;

delete [] myDogs;

return 0;
}

main.cpp holds the code for the actual program. It only needs to include the header file for the class, not the actuall code file (Dog.cpp). Dog myDogs[5]; simply creates an array of 5 Dogs, just like using any other built in data type.

In order to access each individual Dog, simply include its index number in the brackets, and use it as you would any normal class. This example simply sets their age and displays it.

Multi-threading
So far we’ve seen how to make games using a while loop that gives each process its own turn, lets look into getting the game to run all these steps at once. Here is some example code:

#include
#include

using namespace std;

void myFunction( void* number){

int myNumber = *(int*)number;

cout << “This is prcosses number: ” << myNumber << “\n”;

_endthread();

}

int main(int argc, char *argv[])
{
int tempNum[10];

for( int i = 0; i tempNum[i] = i;
_beginthread( myFunction, 0, (void*)&tempNum[i]);
}

system(“PAUSE”);
return 0;
}

The new commands introduced here are _beginthread() and _endthread(), both included in process.h. _beginthread() takes 3 parameters, first is the function you want to run, in this case myFuntion, second is the size of the stack (just set this to 0), and third, any parameter you want to send. If no parameters are to be sent, the function still must accept a void* parameter, when actually calling _beginthread() set the last parameter to 0. For example:

void myFunction( void* dummy){

….
code here
….

}

_beginthread( myFunction, 0, 0);

Notice the way the parameter is sent, its converted from what ever type it orginally was to void*, this allows any data type to be sent using this function. Also make sure to place the ‘&’ infront of the variable, this will pass the memory address the variable points to instead of the value.

In the function being called by _beginthread() you need to convert any parameters (unless if there are none) back to their original data type. Just replace the int in “*(int*)number;” to whatever datatype you need, and you can continue using the information as usual.

_endthread() will terminate the thread, its not necessary to use it since it will automatically be called once the function called by _beginthread() ends.

Each thread doesn’t actually run at the exact same time, processor time will be divided up between the functions, since it happens so fast, it just seems as if they were all running at the same time. When running this code, if the output is not in order, dont worry. Its simply because one or more of the processes were not able to get their output written to screen before the next process starting writting its own.

3 Responses to Cơ bản về C++ – Basic C++ Lessons

  1. I just want to say I am beginner to blogs and really loved your web page. Most likely I’m planning to bookmark your site . You definitely come with very good stories. Appreciate it for revealing your blog site.

  2. I just want to say I am just all new to weblog and certainly savored you’re page. More than likely I’m want to bookmark your blog post . You absolutely come with incredible writings. Regards for sharing your website.

Gửi phản hồi

Please log in using one of these methods to post your comment:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Log Out / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Log Out / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Log Out / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Log Out / Thay đổi )

Connecting to %s

%d bloggers like this: