Intro To C++

wizeman

Banned
Messages
256
Reaction score
0
Points
0
This is the starter to a series of C++ tutorials I will write when I have the time (mainly during my third period class :)). Anyways, this tutorial asssumes you have no background experience in programming (its fine if you do), and may teach a lazy habit or two. Note that I do not have access to a compiler as of writing this, and there may be a glitch or two in the code (Please let me know if you find one).
First off, I will explain the basics:
A compiler is a program that turns your code into a working executable. Some common compilers are gcc and g++.
An IDE (integrated development environment) is exactly what it says - an environment for developing code in. There are many different IDE's available, such as Dev-cpp, Borland, and Visual C++. I recommend Dev-cpp, because it is easy to use, as well as being free. The link is as follows: http://www.bloodshed.net/dev/devcpp.html
All instructions in this tutorial assume that you have Dev-cpp installed.

To compile your code in Dev-cpp, go to Execute - compile. If you want to immediately run your program after compiling, select Execute - Compile and run.

Lets continue by jumping straight into some code for the easiest possible program; Don't worry if you do not understand it, I will explain afterwords what it all does.


Code:
#include <iostream>
 using namespace std;
int main()
{
  cout << "Hello World! ";
  system("PAUSE");
  return 0;
}

OUTPUT:
Hello World! Press any key to continue.

EXPLINATION:
#include - This includes a file, in this case iostream, which defines many common functions for a C++ program (such as cout, endl, etc.) Notice that we have:
#include <iostream>
The < and > signify that it will look in the include directory, which will vary depending on what compiler you use. In this case it is [wherever you install dev-cpp]\include .

int main() Is the entry point, or starting point of your program. This is where all code execution begins.

{ - This is an opening bracket. For now, just realize that int main needs one immediately after it.

cout << - cout, or console out, is used for outputting text to the screen in a console program. For example, If I put:

Code:
cout << "Hello World!";

It would output Hello World! to the screen.

system("PAUSE") - This executes a command prompt command in your program, and is usually not use in programs. For the sake of simplicity, I used it here, I will provide an alternitive for it later. You can put any command prompt command within the quotes, and it will execute it. system() is a function (something you can call).

return 0; - this lets windows know what happened to your program. Typically, if you return a non-zero value the program failed, otherwise it suceeded.

} - This signifies the end to int main(). For now, just realize you need it.


Notice that every line ends with a semicolon. In C++, this signifies the end of a line of code...well, thats not really correct, because whitespace is ignored in C++ ( you can have it span as many lines as you want, or put as many spaces as you want). Well, Im out of time ,I will post a follow-up to this later when I get home.
[/code]
 

wizeman

Banned
Messages
256
Reaction score
0
Points
0
Intro To C++ (Part 2 of 3)

I realize that I cut the tutorial off without finishing it last time, I ran out of time. Ok, I left off talking about whitespace in the last tutorial.

In C++ Whitespace is ignored, meening that:


Code:
cout << "Hello World!";
is the same as


Code:
cout <<
"Hello World!";
The following is wrong however...



Code:
c out << "Hello World!";
You can not put whitespace within a function name.


Case Sensitivity:
In C++, everything is case sensitive. This means that



Code:
cOut << "This is incorrect!";
will not work. This is because the O is capatalized. When I cover variables, this means that an upper-case variable is different from a lower case variable. we'll cover that later.


Now, I will introduce to you every programmers bane....the parse error. These little devils are often produced through typos, or incorrect syntax, etc. Here is our previous example, with one of the semicolons taken out.



Code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World! ";
system("PAUSE");
return 0
}
See how the line with return 0 does not have a semicolon after it? this will produce the following error when you try to compile:

u:\Dev-Cpp\New Folder\main.cpp In function `int main()':
7 u:\Dev-Cpp\New Folder\main.cpp expected `;' before '}' token
u:\Dev-Cpp\New Folder\Makefile.win [Build Error] [main.o] Error 1

You may be thinking "Wow, thats quite a bit of errors for one typo!".
The first line lets you know what function the error was encountered in. In this case, it was encountered in int main(). You may notice several differences between my error output and yours, specifically the "u:\Dev-Cpp\New Folder\main.cpp" portion of your error. This is the path to the file, and will differ depending on where your project is. (for example, C:\dev-cpp\your_project)
The second line is the line that lets us know about our parse error. It is divided into 3 parts.
The number 7 is the line that it encountered the error on. This is not allways completely accurate, but helps you to locate the error. The "u:\Dev-Cpp\New Folder\main.cpp" is the path, as I discussed before.
The last part "expected `;' before '}' token ", lets us know exactly what error it received on that line. In this case, it is just letting us know about our parse error.
The final line just informs us that the compiler encountered a build error while compiling our program.

Say you want to end a line of text in the console...To do so you would use the newline symbol, as I will show you in the example below.


Code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World! \n This is a new line! \n"
system("PAUSE");
return 0;
}
Notice the difference? when run this will produce the following:
OUTPUT:
Hello World!
This is a new line!
Press any key to continue.

NOTE: You do not have a space inbetween the newline symbol (\n) and the previous or next text. For instance, you could have



Code:
cout << "Hello World!\nThis is a newline!";
Just as easily, and it would take the space in front of the text out of the output.


Using Input and Storing data in your programs
This section introduces a more intresting aspect of programming: Getting user input. This section only covers basic methods, assuming I write further tutorials, I will cover it there.

We will now start with the most basic way to get user input, that is through the use of cin. As always, I prefer to jump into code, so if you don't understand anything dont worry, I will explain it afterwords.




Code:
#include <iostream>
using namespace std;
int main()
{
int theNum;
cout << "Please enter a number between 1 and 10.\n:";
cin >> theNum;
cout << "Your number was " << theNum << "\n";
system("PAUSE");
return 0;
}
In that code we introduced quite a bit of new stuff. Lets take it line-by-line.



Code:
#include <iostream>
using namespace std;
int main()
{
You should already know what that does, so I will skip it.



Code:
int theNum;
This is one of the most important parts of the above code: This introduces data storage.

Code:
int- An int stands for integer - it is a basic data structure capable of holding a fairly large number(I cant remember the exact amount).
Code:
int theNum;- this is pretty straight forward, theNum is simply the integers name, and you store data in that particular int by using its name. Please note that C++ is case sensitive - theNum is not the same as thenum.


Code:
cin >> theNum;
cin (or console in) is a method used for getting user input via the keyboard. >> means put into, in this case we are putting what we get from cin into our variable theNum.

Code:
cout << "Your number was " << theNum << "\n";
This line introduces several new things, such as displaying theNum through cout.


Code:
cout << "Hello " << "World!";will produce the same thing as 
Code:
cout << "Hello World!";
You can display nearly anything through cout.

There are relatively few types of data storage in C++, they are listed as follows:

int - this is an integer, it is the same thing as the one shown in the above program. (note that int's only work with whole numbers)
char - A character. Note that this is only one character, not a whole word or sentance.
bool - a boolean value. A boolean is a true or false variable, A - non-zero means that it is true, a value of zero means it is false.
float - Floating Point. A floating point number can hold an extremely large number.
double - Double Precision - The largest of the listed storage types, this holds very large numbers as well as being able to use decimals.

All of the above are used in the same method as an int. Well, thats all for this tutorial, try playing around with the data storage methods I have shown you, as well as with the cin (console in) and cout (console out) operators. In the next tutorial, I will introduce conditional statements and loops.
 

wizeman

Banned
Messages
256
Reaction score
0
Points
0
C++ (Part 3 of 3)

C++ Tutorial 3 - Loops and Conditionals

Welcome to part 3 of my C++ tutorial series I am writing during class. This tutorial will cover if - else statements, while loops, for loops, do while loops, and maybe a few other things if I feel like it.

Before I do anything, I am going to introduce something I probally should have in the first tutorial. Comments. Comments make code much more easily readable, and help when writing tutorials
icon_smile.gif


Code:

int main()
{
cout << "Hello World!"; //This is a comment. Notice the two slashes. These
//signify that everything that follows them is ignored by the compiler. Thus,
//I can put anything here without the compiler giving you errors.
system("PAUSE");
return 0;
}
The above was an example of using comments. Everything on a line after a // is ignored by the compiler. Here is another way of using comments.

Code:

int main()
cout << "Hello World!"; /*This is another comment. This comment can span multiple lines, without having to put the // in front of each. This kind of comment is usefull for comments that take up multiple lines.*/
/* starts a comment, while */ ends one. Now that we are done with that, let us move on.

Lets start with the if loop. In the last tutorial, I posted an example on getting user input and storing it in a variable (an int). The example is as follows.

Code:

#include <iostream>
using namespace std;
int main()
{
int theNum;
cout << "Please enter a number between 1 and 10.\n:";
cin >> theNum;
cout << "Your number was " << theNum << "\n";
system("PAUSE");
return 0;
}
Notice that the above code does not actually inforce that the number is between 1 and 10. If statements are one way to do this. If statements have the following syntax:

Code:

if(arg1 operator arg2)
{
//Do stuff in here....
}
arg1 stands for argument 1, arg2 for argument 2. if arg1 operator arg2, then execute the code within the brackets. Otherwise, do not. This may seem a little confusing at the moment - it's ok, hopefully the following example will help.

Code:

if(variable < 5)
{
cout << "The variable was less than 5!";
}
Pretty simple. The if loop compares if the first argument (variable in this case) is operator (less than or <) than the second argument (5 in this case). If variable is less than 5, the code within the brackets is executed. Next is the else conditional.

Code:

if(variable < 5)
{
cout << "The variable was less than 5!";
}
else
{
cout << "The variable was greater than 5!";
}
The else statement is only called if the if statement is not true (variable is not less than 5). Following is a short list of simple comparison operators that you can use.

== - If arg1 is equal to arg2, this will be true.
!= - if arg1 does not equal arg2, this will be true.
<= - if arg1 is less than or equal to arg2, this will be true.
>= - If arg1 is Greater than or equal to arg2, this will be true.
|| - This is not really a comparison operator, but it is often used with them, so I included it here. It stands for or. An example would be

Code:

if(variable<5 || variable==7)
{
//do sutff....
}
This will be true if either one of the conditional statements withing the if statement is true.
&& - This is not a comparison operator either, but it is often used with them so I stuck it here anyways. It stands for "and".

Code:

if(variable < 5 && variable!=3)
{
//do stuff here...
}
This will be true if both of the conditional statements within the if statement are true.

Now lets see the previous tutorial's example, this time redone to see if it is actually between one and 10.


Code:

#include <iostream>
using namespace std;
int main()
{
int theNum;
cout << "Please enter a number between 1 and 10.\n:";
cin >> theNum;
if(theNum >=1 && theNum <=10)
{
cout << "Your number was " << theNum << "\n";
}
else
{
cout << "The number you entered was not between one and 10!";
}
system("PAUSE");
return 0;
}
Notice the added if and else statements. The if statement checks to see if the number is between 1 and 10, if it is prints the number the user entered. The else statement prints out that the number was invalid. Remember that the else statement is only called if the if statement is invalid.


Loops
The concept of a loop is pretty simple. If the loops conditional statement is true, repeat. Otherwise do not. The while loop is one of the simpler kind of loops, so we will cover it first.


Code:

int i = 0;
while(i<10)
{
cout << i << " ";
i=(i+1);
}
EXPLENATION:
This is pretty self explanatory. while i is less than 10, print the value of i to the screen, followd by a space. while loops can use all of the operators I listed above as well.

OUTPUT:
0 1 2 3 4 5 6 7 8 9

for loops are a little more comples than while loops.

Code:

for(int i=0; i<10;i++)
{
cout << i;
}
Both of those examples do the same thing. The for loop, broken down, is as follows.

Code:
for(int i=0;
This is the initialization section. You can declare and initialize variables within this segment.

Code:
i<10This segment is the conditional statement - while i is less than 10, keep looping.

Code:
i++This segment is executed every time the loop loops once. This segment is typically used for incrementing or decrementing variables.

The Dreaded goto
For any who are not familiar with the goto statement, please skip this section. For the rest of you who may be wondering, the goto loop is available in C++. However, its use is shunned as it creates spagetti code, as well as creating a number of other problems (such as destructors not being called, etc. I will cover destructors later). For this reason, I will not cover the goto loop within this tutorial.


Conclusion
To wrap up this tutorial I will post a simple menu example. There are better ways to do this, which I will cover later.


Code:

#include <iostream>//Includes common functions and such
using namespace std;//Use the std namespace

int main()//Program entry point
{
bool done=false;//loop quit variable
while(done!=true)//The main program loop.
{
cout << "1 - Print a message.\n 2 - quit the program.";//Print the menu
int choice=0; //Declare the variable choice and set its value to 0
cin >> choice;//Get the user input and put it in choice
if(choice==1)//if choice equals 1
{
cout << "A random Message!\n";//print the message
}
else//Otherwise
{
done=true;//quit the loop
}
cout << "\n\n\n";//print a few newlines
} // End the while loop
}//end the program


Hope this tutorial helped someone.
 

digitalfarm

New Member
Messages
290
Reaction score
0
Points
0
hmm..seems very interesting.Now that schools out and really would like to learn programing
 

AsPeRiTy

New Member
Messages
284
Reaction score
0
Points
0
wow great tut.. if only I could get my hands on a copy of visual studio lol
 

Iceman

New Member
Messages
308
Reaction score
0
Points
0
A fairly good tutorial. I give it a thumbs up and would pass it along to anyone willing to learn it. Keep up the good work! :)
 

Mikek

New Member
Messages
246
Reaction score
0
Points
0
Just a little tip, to clear the console in a windows C++ program you can use
system("cls");
 
Top