Learning C++ [Tutorial]

Deathcrow

Power member.
Reputation
0
C++ Programming

I hope you guys enjoy this tutorial. If you have any questions, feel free to ask. I will probably add one part a week so that there is plenty of time to learn everything in the available part(s) before moving onto the next one. If you like it, show that you do. :)

Free C++ Compiler: Bloodshed Dev-C++

Part 1: The Basics
We will start off with the very basics.

The overall structure of a C++ program contains one function named main(), called the driver function. All other functions are invoked from main().

Every statement inside the function must be ended with a semicolon, ;.

A keyword causing the appropriate value to be returned from the function is return. The statement return 0 in the main() function causes the program to end.

When writing code you want to make sure there is a structure so that it is easy to read and follow. This will make it easier for you or anyone else to understand what the code will do.
1kyFP


cout << "insert text here" is used to display text to the person using your program. This is easily used to ask the user for input.

cin >> "insert variable here" is used to store the user's input as a variable.

1kyKk


Comments are explanatory remarks in the source code added by you, the programmer. They begin with // and continue to the end of the line. Block comments span across two or more lines. These begin with /* and end with */. These are useful for sections with many comments, such as problem background of logos. This can also be used to temporarily "comment out" a section of a program while you debug it. They can also be used for your headings. Here is an example of how I usually use comments:
1kAKk


A variable name is referred to as an identifier. All variable names must be declared. This means you need to list the name and type. Data types include int, float, double, char,....(there are more but these will be sufficient for now). Variables of the same type may be declared in the same statement separated by a comma. To name identifiers there are a few rules you must follow:
  • First character must be a letter.
  • Other characters may be letters (a-z, A-Z, _ ) or digits 0-9.
  • Cannot use C++ keywords (reserved words - see next image).
  • Cannot have blanks within identifiers (spaces).
  • Use descriptive names (Not necessary, but very helpful).
1kz6U


To give numeric values to variables you need to use the assignment operator (=) which is what you know as the equal sign.
1kyXv


Also, you can use constant qualified variables. For example you can use const double PI = 3.14159 to declare the variable PI as that constant. It cannot be modified later in the program. To use it simply insert "PI" anywhere that it is needed in the program. I recommend using all uppercase characters to name constants as it makes them easier to identify. You could also use what I use:
1kzj4


I want to make sure that you guys understand that = does NOT mean equal. For example:
1kzeB


C++ Data Types
I will go into more detail about the data types now.
  • Integers - int, short int, long int, unsigned int, etc.
  • Real numbers - float, double, and long double.
  • Characters - char.
  • Boolean - bool.
  • Strings - string. (using string class, string.h)

Integers are numbers without decimal points. Each one has a different amount of memory, a different range of numbers so to speak.
1kzWz


Real numbers are numbers with decimal points. They may be in scientific notation or in fixed-point notation. If you exceed the range there can be overflow or underflow errors.
1kzY8


A character consists of any single symbol enclosed in single quotes. Escape sequences such as \t, \n, \r, \v are regarded as a single character. You can think of a character as essentially acting like an integer. Based on the table below you can see that these two commands would have the same effect:
char c1 = 'A';
char c1 = 65;

1kA7g


Let's go into more detail about using cout and cin.
cout << [variable, expression, or text (in double quotes)]
cin >> value
<< is referred to as the extraction operator. >> is referred to as the insertion operator.
1kAfV




If there is text inside the double quotes, it is referred to as a string. A string is any combination of letters, numbers, and special characters enclosed in double quotes (delimiter). A delimiter is a symbol that marks the beginning and ending of a string, but is not part of the string.

The backslash (\) can be used at an end of a line to indicate that the string constant will be continued on the next line. The following two statements are equivalent:
1kAnO


C++ does not automatically advance the display to the next line after using cout. To do this you need to use endl (endline) or \n (\ is used to start an escape sequence and n is for "newline").
1kArO


Here are some more escape sequences:
1kAuc


To use C++ for programs related with math you need to use arithmetic operations. These look like algebraic expressions and consist of sequences of operands and operators. An operand is a variable, constant, or any value. Most common operators are +, -, *, /, and %.
1kATr


Try to avoid mixed-type operations unless they are necessary and intentional. If a real result is converted to an integer it is chopped off after the decimal point, not rounded off. If a real value is assigned to an integer variable the same thing happens. If an integer value is assigned to a real variable, it is promoted to a real (decimal point added).
1kAXl


Here is the order of operator precedence:
1kAYT


++ is the increment operator. -- is the decrement operator.
For example:
x++ means x=x+1
x-- means x=x-1

When these are placed in front, incrementing or decrementing occurs BEFORE value assigned. When placed in back, occurs AFTER value assigned.

1kB2I


You can also use compound assignment operators as a "shortcut".
For example:
A += B; is the same thing as A = A + B;
A -= B; is the same thing as A = A - B;
A *= B; is the same thing as A = A * B;
A /= B; is the same thing as A = A / B;
A %= B; is the same thing as A = A % B;

To use certain math functions you must use the cmath or cstlib headers: #include <cmath> or #include <cstlib>

It is important to remember that all trig functions in C++ use radians not degrees. Also, the "log" function calculates the natural logarithm. To calculate the base 10 logarithm use the "log10" function.

Here are some of the math functions:
1kBgb


Alright, I think it is time for you to make a simple program to calculate the area of a circle. Try to do this yourself given what you have read and learned so far. Remember the area of a circle is PI*r^2. You will need #include <cmath>. Below is an example of how it could look:
1kBkJ


This would be the output if the user entered 20 for the radius:
1kBkT


I think this is a good place to stop the tutorial for now. One of the things I will cover in the next part is formatting.


Video:
Courtesy of @"Mr.Anderson"
[video=youtube]http://www.youtube.com/watch?v=_3RV_ImD6GE&feature=youtu.be[/video]



Part 2: Formatting
In C++ there are ways to format your output, the things that the uesr of your program will see.

Output values are formatted in C++ by inserting I/O manipulators (parameterized) into cout statements for printing.

An example is cout<<setprecision(6)<<x<<y; where "setprecision(6)" is the I/O Manipulator.

These usually affect all outputs from that point on so there is no need to include the one your previously used in every cout statement after, but this might be compiler dependent.

In order to use I/O manipulators to format output you must have the header#include <iomanip>. The basic form for using I/O manipulators is: cout<<manipulator(parameter);.

Here is a list of several common I/O manipulators:
  • setfill (int f) - This sets the fill character to f.
  • setprecision(int p) - This sets the precision of a floating-point number to p.
  • setw(int w) - This sets the field width to w.
  • Setiosflags(long f) - This sets the format flag specified by f.
  • resetiosflags(long f) - This returns to default for the flag specified by f.
  • setbase(int b) - This sets the base of numbers output to be b (must be 8, 10, or 16).
  • showpoint - Directs the output to include trailing zeros.

Here are some examples of how you can use these.
setw():
1o56d


setprecision():
1o57O

1o58n


showpoint:
Two forms - cout<<setiosflags(ios::showpoint) and cout<<showpoint
1o5bd

1o5by


setfill():
1o5ce


setiosflags(ios:: ):
cout<<setiosflags(ios::flag)
cout<<setiosflags(ios::flag1|ios::flag2|......)

Flags include:
  • left - left justify the output
  • right - right justify the output
  • fixed - use fixed-point notation (not scientific notation)
  • scientific - use scientific notation
  • showpoint - include trailing zeros


For printing monetary values it is necessary to use I/O manipulators.

For example:

double income = 7842;
cout<<setprecision(2)<<setiosflags(ios::fixed|ios::showpoint)
<<"Income = $" <income;

Output:

Income = $7842.00


Here is the code, input, and output of an example showing how these manipulators work:
1orHx



Part 3: Selection Structures
It is often necessary in programming to make decisions, where the program will perform different tasks based on the results of some test.
  • So far, all of our C++ programs have consisted of straight line control, or a series of commands executed in order with no branches.
  • Now we will talk about selection structures (also called decision structures or branching structures).
  • Two types of selection structures will be introduced: if structures and switch structures.

The flowchart below shows the difference between straight line control structures and selection control structures.
1CWyq


if control structures are used to make decisions. Relational expressions are evaluated as true or false. The block of statements are only executed if true.

if control structures follow this form:
if (relational expression)
{
statement(s);
}


To use these kinds of structures you must use relational expressions. This is what produces the result of true or false. It compares values of two arithmetic expressions.
1CX3A


Sometimes you will need to compare characters and strings. This is essential in alphabetizing names or in using characters to make decisions in selection structures. Single characters are treated as integers and are compared based on their ASCII value. ('A' is valued at 65 and 'a' is valued at 97 therefore A < a)

Strings of characters are compared one character at a time. If the first character in each string is the same, then move on and compare the second character, etc. They are essentially ordered as they might be in a dictionary, so
"sent"<"sentence"<"sentences"

Sometimes logical operators are used for more complicated logical tests for branching. For example, instead of executing a block of statements if x>2, we might want to execute them if x>2 and if x<7.

The logical operators that are commonly used:
  • AND (&&)
  • OR (||)
  • NOT (!)

The symbol && represents the logical function AND. It combines two relation expressions. The combined expression is true only if BOTH expressions are true.

The symbol || represents the logical function OR. It combines two relational expressions. This combined expression is false only if BOTH expressions are false.

The symbol ! represents the logical NOT function. It reverses the result of a relational expression.

Here is the precedence of operators:
1CXtS


Simple if/else control structures:
  • One block of statements is executed if the expression is true and another block if the expression is false.
  • Braces are optional if there is only one statement in the block.
1CXxc


Examples:

if (x<12)
----cout << "smaller than twelve";
else
----cout << "twelve or larger";


Note: No braces are needed since each block contains only one statement.


if (Hours > 40)
----{
----cout << "You worked overtime";
----Pay = 40*Base_Rate + (Hours - 40)*Overtime_Rate;
----}
else
----{
----cout << "No overtime worked";
----Pay = Hours*Base_Rate;
----}


Nested if statements are very common in programming. A nested if statement is an if statement that is the target of another if or else statement. Proper indentation helps us to understand the structure (although the compiler doesn't care).
1CXEI


Try to figure out the results from below and then check to see if you were right by compiling it.
1CXFq


if-else-if structures:
  • Shifts program control, step by step, through series of statement blocks
  • Control stops at relational expression that tests true
  • Some programming languages have an "elseif" command. In C++, using else if(relational expression) simply implies that the if statement represents that block of instructions to be represented when the else condition is true.
  • Proper indentation is important for readability.
  • In general, an else statement always refers to the nearest if statement that is within the same block as the else and not already associated with another else.[/b]


1LjsD


Try this one below:
1Ljtx


You can check the answers from above by simply compiling the code on the left side of the picture.

Note: The indentation used in that code is extremely important. Without that indentation it would be much harder to read and understand the code. (even though it doesn't matter to the computer)

Below is an example of using "switch" structure.
1Ljyu


The next image is the same program but allows for character input instead of numerical input. (for the choice)
1Ljzh





 
Insanely nice tut Deathcrow.

If I didn't already know C++ this would be immensely helpful.

To everyone else learning this language, follow this as a guide. Goes into to perfect explanation and shows examples.

10/10 man.

Also, grats on admin lol
 
Dude this is awesome.

granted some of it i could perhaps do with a bit more tutoring, but everything is explained very well. the pictures are a little big but if you zoom your page out a little they are real help full. i went ahead and dug up a c++ textbook ive had for a while and might try to teach myself, i learnt a small amount a short while ago, but not as much as all of this.

you should definitely hold some tinychat sessions, it was a topic brought up a while ago, and, i definitely think that it would make it easier to learn :D

but yeah, i have bookmarked this thread and will continue reading when i have some more time :D

thanks for the guide DeathCrow
 
No problem, guys. If you need help with anything covered here, just add my Skype (Deathcrow_MMO) and I will help you. You could also just post any of your questions/concerns here.

This is only part 1 and is the basics. There is lots more to cover so try to get comfortable with everything covered here before I release the next part.
 
Very nice guide man, This is so well detailed, but wouldn't it be easier for you, as well as the learners to have videos showing it? I don't know about others, but I learn better from hearing it and actually seeing it done by someone.

Just a though ^^.
 
Darry said:
Very nice guide man, This is so well detailed, but wouldn't it be easier for you, as well as the learners to have videos showing it? I don't know about others, but I learn better from hearing it and actually seeing it done by someone.

Just a though ^^.

A video would pretty much only be useful for showing you how to create a program using whatever I use in that given program I video myself making. This guide tells you things a video can't.

But I do think creating a video to go along with this would be beneficial.

I will see what I can do.
 
Thanks for the tutorial! :) Should be useful in the future if I need to learn C++ for anything.
 
Stewie said:
Thanks for the tutorial! :) Should be useful in the future if I need to learn C++ for anything.

Even if you don't need to learn C++ you could still do it just for the fun of it. It is kind of cool being able to learn something, apply that knowledge, and then have something that you can actually use as a result. :)

EDIT: 1,500 posts.
 
Deathcrow said:
Stewie said:
Thanks for the tutorial! :) Should be useful in the future if I need to learn C++ for anything.

Even if you don't need to learn C++ you could still do it just for the fun of it. It is kind of cool being able to learn something, apply that knowledge, and then have something that you can actually use as a result. :)

EDIT: 1,500 posts.
True :p Also grats :)
 
programming is cool to me because it allows you to be creative through being very technical and precise.

its very rewarding actually making something in any case, especially programming
 
gogeta said:
programming is cool to me because it allows you to be creative through being very technical and precise.

its very rewarding actually making something in any case, especially programming

Exactly. I love the feeling of finishing a long and tough programming project. Especially when you compile it and everything runs smoothly. :)
 
Mr.Anderson said:
Insanely nice tut Deathcrow.

If I didn't already know C++ this would be immensely helpful.

To everyone else learning this language, follow this as a guide. Goes into to perfect explanation and shows examples.

10/10 man.

Also, grats on admin lol

Want to make a video showing how to use the things I covered in the first part of the tutorial? =D

Would be awesome if you did a video tutorial on every part that I did.

EDIT:

I don't have a mic and I think it would be best if the person had commentary to go with it.
 
Deathcrow said:
Mr.Anderson said:
Insanely nice tut Deathcrow.

If I didn't already know C++ this would be immensely helpful.

To everyone else learning this language, follow this as a guide. Goes into to perfect explanation and shows examples.

10/10 man.

Also, grats on admin lol

Want to make a video showing how to use the things I covered in the first part of the tutorial? =D

Would be awesome if you did a video tutorial on every part that I did.

EDIT:

I don't have a mic and I think it would be best if the person had commentary to go with it.

I have a mic and a sexy voice, I can explain it if you want.
 
Deathcrow said:
Sure I have. =p

He submitted a song in the Singing Contest.

dayum.

you got me there.
 
This will be really good for people new to C++ like myself, thanks for posting :D
 
Thomass said:
This will be really good for people new to C++ like myself, thanks for posting :D

No problem. :)

Will be adding the next part in a few days.
 
Back
Top