C++ Lesson 2: Introduction

You can talk about anything. (please read forum rules before posting)

Moderator: thunderchero

Post Reply
User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 2581
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

C++ Lesson 2: Introduction

Post by Flocke » Thu Jul 05, 2012 9:08 am

C++ Lesson2: Introduction to C++ development

Previous: C++ Lesson1: Preparations
Follower: C++ Lesson3: Classes

Ok, well, we already had a lesson 2 but obviously it's been too much for the n00bs. So I decided to split that topic now and become more basic with better explanations. That'll be more lessons but therefore simpler and shorter steps. Ok there's much to read but far less to work!
Hope you feel more comfortable to that and we gain more participators and better activity again.
Content mostly keeps same, but doesn't harm to read it twice. ;)

---------------------------------------

The lesson before I showed how to set up MinGW GCC with Code::Blocks as a development environment. We also did build a simple "Hello World" program to proof the installation works.
This lesson I'll explain, give you some samples and you try modify building your first own application.
That is much more for me to write than for you to read and practice.
You can't do much wrong, and don't forget, even compile and runtime errors help to learn on the subject of programming :!:

As by of now all of us (should) have a working environment to test, now is time for more testing and discussion. :)
Most faults you can get around with just some try and error. If not, here I am.
And I'm already happy for the dumbest questions when that means to get some better activity!

=======================================
code structure

You probably already noticed all the different colors the code is represented in by your Editor.
Further you probably also noticed the line indentions.
Both just make the code much more readable and you'll soon find a grasp on it.
For the compiler neither of them matters.

Important for code structure mainly are the braces, the swung brackets.
There are always two of them, one opening, one closing. They either define a scope or a namespace.
A scope means that e.g. as a function body, variables used inside are local so you don't have to care on names already used outside, and variables get freed automaticly as soon as the function is left so long they are no pointers.
If you put your variables outside of any scope, e.g. directly inside a namespace, they are called 'global' as they can get accessed from any code. You should avoid global variables, they lead to bad programming style and maintenance.

If you now ask 'What is a variable?' you really show you've never went into programming before. But that's no problem for this course, just ask whatever you don't understand. A variable is just a specifier for a piece of data you're working on.
That data is either on stack or in heap memory. Both essentially is just memory aquired from your system memory so called ram. The difference is that the stack is what your code gets processed in and data is always put and read from top only and as soon as a function gets left all it's local data get's removed from stack again.
The heap on the other hand is referenced by pointers and keeps there disregarding your code flow. On older operation systems it doesn't even get freed automaticly when an application closed. So we keep with local variables stored on stack for now.


Now lets go through the lines of the "Hello World" example of last lesson.
#include <iostream>

using namespace std;

int main()
{

cout << "Hello world!" << endl;
return 0;
}
Lines beginning with a # symbol are pre-processor directives, so called "macros". They get evaluated before the compiler is invoked when you build an application. In this sample there's only one single include to link in a different file named "iostream". You could copy the whole content of that file and gain the same.
iostream is part of the std library and defines cout and endl as well as the << operator on it plus many others not used in this example ofc.
To avoid naming conflicts it encapsulates all defined variables, functions and classes in a namespace. As Lathon told last lesson, "using namespace std;" tells the compiler to get all of these out of their namespace and allows you to access them directly, so you've less to type. Still they are accessible by their namespace, so if you have your own cout defined you could print std::cout to access the one defined by iostream.

In this sample there's just a single function named 'main'. main is a special function that is called by the os when you start the program. In Windows gui applications it looks a bit different, but for console applications and linux coding "int main()" is standard. In Java you define a main function as part of a class body, here in C and C++ it's always a standalone function.
In the end of that function you return 0 to the calling function, in this case to tell the os that no errors occured. The return is of type int which is an integer.

Let's do some practice.

=======================================
C++ basics

Start with previous "Hello World" example.
Open your main.cpp, we'll add a while loop that does not halt before key input.

Remove following portion of your main: cout << "Hello world!" << endl;
and if from previous lesson also: #include <cstdlib> and system("PAUSE");
We don't need this anymore.

Instead place this into your main:

Code: Select all

string input;
while(input.compare("exit") != 0)
{
	cout << "post some stuff" << endl;
	getline(cin, input);
}
What this does is define a local string variable named "input". 'string' is a class defined in #include <string> header that got already included by #include <iostream> header in turn. This class initializes with empty content by default.
Then there comes the while loop. It first checks whether your input variable holds the text "exit" and only if that's not the case so there's either a negative or positive result of comparison (see c++ std library reference) it executes what's inside the braces.

At start input string is empty, so inside while it prints "post some stuff" to the console window.
Then a line is read from cin, the console input stream, to the "input" variable.
Other than with cout no >> operation is used. That is to avoid parsing errors and get a full line. Don't care much on it.
The while then keeps looping until you typed in "exit" what the while keeps checking for.

On further coding from time to time I'll add some comments to explain the code.
Comments are disregarded by the compiler and there can be added as many you want.
It is either a full line started by // or a flexible portion enclosed by /* */ tags.

One of the main important constructs used in a program are the if and else clauses.

Code: Select all

if(something){
	// then do this
}
else{
	// do something else
}
When there's just one code statement to execute (ended by the semicolon), you can omit the braces. You also don't need to add an else clause. And if you want multiple choises you can put an else if(){} clause in between which is composed of a one statement else introducing another if clause.

Back to your code, we'll count the while iterations and handle leaving the loop on our own featuring the break; statement.
Before of the while, define another variable. This time make it an integer and initialize it with 1 for first while iteration:

Code: Select all

int myint = 1;
Then change your while to while(true) to always keep looping.

Next on top of your while body in the braces, add the following code:

Code: Select all

if(myint > 20)
{
	// the iteration check could be done in while check too ofc,
	// but this way we do some appropriate output
	// to see it you can add back system("PAUSE"); if you want
	cout << "too many attempts, leaving";
	break;
}
After getline reading your input place:

Code: Select all

// next check for some input values
if(input.compare("BotF") > 0)
{
	cout << "nothing is greater than BotF, type something else!" << endl;
}
else if(input.compare("Star Trek") == 0)
{
	cout << "keep talking, I give you another five attempts" << endl;
	myint -= 5;
}

// last, increment the myint variable
myint++;
Putting it together:

Code: Select all

#include <iostream>

using namespace std;

int main()
{
	int myint = 1;
	string input;
	while(true)
	{
		if(myint > 20)
		{
			// the iteration check could be done in while check too ofc,
			// but this way we do some appropriate output
			// to see it you can add back system("PAUSE"); if you want
			cout << "too many attempts, leaving";
			break;
		}

		cout << "post some stuff" << endl;
		getline(cin, input);

		// next check for some input values
		if(input.compare("BotF") > 0)
		{
			cout << "nothing is greater than BotF, type something else!" << endl;
		}
		else if(input.compare("Star Trek") == 0)
		{
			cout << "keep talking, I give you another five attempts" << endl;
			myint -= 5;
		}

		// last, increment the myint variable
		myint++;
	}
	return 0;
}
This type of while is often used for games and so called the main game loop.
Well, actually they also mean checking for windows messages and other input before doing game calculations, but don't think that's defined strictly somewhere.
You can play around with that now.

=======================================
build your own application

Now here comes the fun part.

I want you to perform some action in that while loop!
Do some crazy calculations, implement a little question and answer game, whatever.

When in search for more operations or whatever, one very good reference I've already posted is http://www.cplusplus.com e.g. -> http://www.cplusplus.com/doc/tutorial/operators/
Btw, to keep printing to same line, skip "<< endl" and just use cout << myint; if you want.

Have some fun and share your results. 8)

Haleth
Ensign
Ensign
Posts: 23
Joined: Sat Sep 25, 2010 2:00 am
Location: Germany

Re: C++ Lesson 2: Introduction

Post by Haleth » Sun Jun 16, 2013 4:59 pm

ok so far it seems ok

i edited a few changes to bring it like i want it

and i used german language no problem i hope

http://www.file-upload.net/download-772 ... o.rar.html
Anyone who has never made a mistake has never tried anything new.

Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson 2: Introduction

Post by Dr_Breen » Sun Jun 23, 2013 6:24 pm

ha wir haben einen interessenten mehr. flocke wo bleibt lektion 4? :-)
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55

User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 2581
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

Re: C++ Lesson 2: Introduction

Post by Flocke » Sun Jun 23, 2013 7:10 pm

Dr_Breen wrote:ha wir haben einen interessenten mehr. flocke wo bleibt lektion 4? :-)
wo sind die andern 3? :lol:
ich denk es ist sinnvoller ich wart damit bis ich nen vernünftiges Pluginsystem fertig hab + paar Beispiele ;)

Post Reply

Return to “General Chat”

Who is online

Users browsing this forum: No registered users