C++ Learn C++ Programming FAST A Project-Based Introduction To Programming B011DO9JE4
C++ Learn C++ Programming FAST A Project-Based Introduction To Programming B011DO9JE4
Programming
by Kennith Perry
All Rights Reserved. No part of this publication may be reproduced in any
form or by any means, including scanning, photocopying, or otherwise
without prior written permission of the copyright holder. Copyright 2012
Table of Contents
1. Chapter 1: Getting Started with C++
2. Chapter 2: Variables
3. Chapter 3: Constants
4. Chapter 4: Expressions and Structures
5. Chapter 5: Fun with Functions
6. Chapter 6: Getting Classy with Classes
7. I Need Your Help
8. Check Out My Other Books!
Unless your program is very, very short, it isnt going to work perfectly the first time your
compile and build it. The next step is to run the program to see how it works.
Debug the Program
Debugging is one of the most frustrating aspects of programming! If you program doesnt
run like you expect it to, then you have to go back to your source code and check it for
errors. Then will need to compile, build, and run it again. If there are still problems, you
will have to repeat the process.
Dont get discouraged if you initially spend more time debugging a program than you
spent writing it! Thats to be expected when you are just learning a new language, and
your skills will improve over time.
Example
For this example, we are going to create your very first C++ program. Here is the source
code you will need to type into your source code editor:
You need to type the text and symbols in just as they appear. Well talk about what they
mean after we run the program.
Once you have everything typed in correct, save your file as main.cpp. This will be your
source code file. If you are using Coding Grounds environment, click on the button that
says Compile.
Next, click on the button that says Execute.
This is what you should see on your screen:
The computer displayed on the screen exactly what you had in double quotes on line 7!
Now lets dissect the program to figure out how it worked, line by line.
Line 1: #include <iostream>
The hashtag symbol tells the compiler to include a standard section of C++ code at this
point in the source code. In this case, the standard code to be included is a header named
iostream, which facilitates input and output.
Line 2: using namespace std;
Imagine you have a brother named Bill and a co-worker named Bill. If you are at work
and mention Bill to a co-worker, they will probably first assume that you are talking about
the Bill you work with.
The using namespace command in C++ works somewhat like that. Imagine how your
program is going to react if you try to use two totally different variables with the same
name in one program. You can expect some unexpected results!
One way to solve this problem is by setting up namespaces. Now as a beginner you dont
need to worry about any other namespace than std, but advanced programmers may set up
separate namespaces so that a variable can mean one thing in one part of the program (like
Bill your co-worker at work) and another thing in another part of the program (like Bill
your brother when you are at home).
In this program, we are simply indicating to C++ to use the standard namespace.
Line 3: int main()
This tells C++ that the following code is the main part of your program. It sets main up as
a function (which we will talk about later) that returns an integer value when it is finished
running. For now, recognize that this signals that what follows is going to be your main
program.
Line 4: { and Line 6: }
Everything between the { and the } constitutes your main program. Think of them as the
beginning marker and end marker.
Line 5:
cout << Hello Human! This is your computer communicating. << endl;
This command takes whatever you have in double quotes and displays it to the screen.
The compiler sees the cout << and realizes that what follows is going to be output. The
text in double quotes is called a string, which is basically a group of characters strung
together. The << endl means to end the line, so anything else that follows will appear on a
new line (and not the same line). The ; indicates the end of the instruction.
Line 6: }
Again, this signals the end of your program.
A good way to practice writing C++ programs is an online compiler like the one found at
Coding Ground. All examples shown in this book were done in the online compiler at
Coding Ground.
A Few Notes on Syntax
As mentioned earlier, programming languages have grammar rules called syntax. One key
point that needs to be made before we go on is the use of the semicolon ; to signify the end
of a command. Dont leave out the semicolons or you will get error messages when you
try to compile your program.
You probably also noticed that cout (the simplest output command we have in C++) is
followed by a <<. Dont leave this out!
Online Resources:
2. Chapter 2: Variables
A variable represents a space, set aside in computer memory, to hold a value. When the
program needs to know that value, it can access it through the name of the variable. You
can think of it as a box in computer memory to hold values.
When you set up a variable in C++, it needs to know two things about: its name and what
kind of value it will be storing. Its obvious why it needs a name (so it can find it!). The
reason it needs to know the type is so that it can set aside enough space in memory to hold
it, and so it can correctly interpret what you store in that space. You might think of it as
selecting the correct size box to hold the value.
Variable Names
A variable name, or identifier as it is sometimes referred to, consists of a sequence of
letters, numbers, underscores. A variable name can begin with a letter, but never with a
number. You can begin a variable name with an underscore _, but that is not
recommended because it might conflict with the name of an existing reserved keyword.
C++ is case sensitive, which means that the word var1 is different from Var1 and VAR1.
Keep this in mind when writing your source code!
Its a good practice to give your variables names that describe what they are. For
example, if you have a program that calculates various features of a right triangle, you will
probably have a variable to hold the area of the triangle; that variable should be named
something like area, or areaTri, rather than var1. It makes it easier to follow your code
when using descriptive names, and makes it easier to track down mistakes.
One common practice is to always have variable names begin with a lowercase letter.
Suppose you have a variable for the street address of a customer. This is a common way
to identify that variable: customerStreetAddress. Notice how it starts with a lowercase
letter, then each new word is capitalized?
Some people go a bit further, by adding a prefix to the beginning of each variable name
that represents its data type. So a floating point number for the area of a triangle might be:
floatAreaTriangle.
There are no hard and fast rules, other than the basic syntax for variable names. You can
use whatever variable names make sense to you, but just keep in mind that when you use
them in your program they (1) must be spelled to match their original declaration in your
code and (2) must use the same capitalization.
Keywords
You cannot have a variable name that matches a reserved keyword. Some common
keywords are things like main, if, int, virtual. At the end of the chapter you will find some
links to online listings of reserved keywords in C++.
Variable Type
As already mentioned, when you set up a variable in a program you need to indicate the
type of data it will be storing. This is referred to as the variables data type. Here is a list
of the most commonly used data types:
6. Name: char
1. Character or small integer, size is 1 byte
2. Range is Signed 128 to 127 and Unsigned 0 to 255
7. Name: short int (short)
1. Short integer, size is 2 bytes
2. Range is Signed -32768 to 32767 and Unsigned 0 to 65535
8. Name: int
1. Integer, size is 4 bytes
2. Range is Signed -2147483648 to -2147483647 and Unsigned 0 to
4294967295
9. Name: long int (long)
1. Integer, size is 4 bytes
2. Range is Signed -2147483648 to -2147483647 and Unsigned 0 to
4294967295
10. Name: bool
1. Boolean value, size is 1 byte
2. Only two values: true or false
11. Name: float
1. Floating point number, size is 4 bytes
2. Range is approximately 7 digits
12. Name: double
1. Double precision floating point number, size is 8 bytes
2. Range is approximately 15 digits
13. Name: long double
1. Long double precision floating point number, size is 8 bytes
2. Range is approximately 15 digits
Signed means that the values can be positive or negative; unsigned means only positive
values can be used.
Declaring a Variable
To setup a variable to use in your program, you declare it. Suppose you need a variable to
hold an integer (whole number) value, and you want to call it count. Here is how to set it
up:
int count;
From that point on in the program, whenever you use the variable name count the program
will assume you are referring to whatever the value is that is stored in count.
You can also declare a value and give at a starting value, called an initial value. Lets say
you want count to start out with a value of 0.
int count=0;
You can also declare multiple variables at the same time, like this:
int a, b, c;
float x, y, z;
You can initialize them all, too:
int a=1, b=1, c=2;
float x=1.0, y=-2.1, z=1.0;
Assigning a Value to a Variable
Lets say somewhere in your program you need to change the value of count to 1. Its
unbelievably easy:
count = 1;
What if, say, you need to add 1 to whatever is already stored in count? There are two
ways to do this:
count = count + 1;
count = count++;
Both of these commands do the same thing. Here is what the compiler sees when it
encounters this instruction: take the existing value of count, add 1 to it, and then store the
new value in count.
Input and Output
All programs involve some kind of input and output. Input is information you provide to
the program, and can include files, characters you type using keyboard, mouse
movements, etc. Output is what the computer provides: it could be the results of a
calculation, or displaying an image, or displaying the contents of a file.
Since this book is aimed at beginners, we are going to limit the input and output to
something simple: input will be what you, the user, type in at the keyboard when
prompted by the program; output will be information, such as text or numbers, that the
program displays on the screen.
Lets create a very simple program that asks for some input and gives some output.
Lines 6 through 11 make up the main program. Everything between the curly braces { and
} make up the body of the program. The first command is on line 6, and declares
variables x and y to be of data type integer.
Online Resources:
List of Standard C++ Keywords:
http://en.cppreference.com/w/cpp/keyword
List of Microsoft C++ Reserved Keywords:
https://msdn.microsoft.com/en-us/library/2e6a4at9.aspx
3. Chapter 3: Constants
Constants are values that do not change. You can access them to find out what is stored
in them, but you cannot change their value. In C++ there are two types of constants:
literal and symbolic.
Literal constants we have already encountered! Remember when we said count = 0?
The 0 is a literal constant, as are all the other alphanumeric characters. For example, if
you x = 1.58 then 1.58 is a literal constant.
Symbolic constants are somewhat like variables in that you refer to them by name, but
their value can never be changed. Here is an example of how one would be defined:
constant MAXSIZE = 255;
From this point forward, anywhere the compiler sees the name MAXSIZE it substitutes
the value 255. Suppose you use this value about 15 times in your code, but then you
realize is should be 256. You only have to change it in one place where you defined it
and then recompile the program.
You will notice that in the example MAXSIZE is capitalized; this is not necessary, but
rather a common habit with older programmers. By doing this, it makes it easy for you to
identify where the constants are in your program.
X && Y
X || Y
!X
True
True
True
True
False
True
False
False
True
False
True
False
True
True
False
False
False
False
The only time an && expression is true is when both operands (in this case, X and Y) are
true. The only time an || expression is false is when both operands (in this case, both X
and Y) are false. The ! operand inverts the value of its operand; if it is True, !True
becomes False.
The logical operators are usually comparing the result of comparison operators. For
example, lets say a has a value of 5 and b has a value of 10. If we have this comparison b
> a, it would have a value of True because the value of b, which is 10, is greater than the
value of a, which is 5.
Lets suppose we want to make sure a is a positive value and b is a negative value. Here is
how we would write that in C++: (a > 0) && (b < 0).
Based on the truth table we talked about, the only time this logical expression will ever be
true is if the left hand side (a > 0) and the right hand side (b < 0) are both true. Otherwise,
the expression will be false.
What if we wanted the expression to be true if either condition is met? We would write
this: (a > 0) || (b < 0). The only time this expression would be false is if neither condition
is met.
Flow Control
One key aspect of programming is controlling how your program flows, or which
instructions it executes. This requires the use of one of three programming structures:
sequential, decision, and repetition.
Many years ago a mathematician named Djikstra proved that every program we could ever
need to write can be done using just these three control structures. You can think of them
as the building blocks of your program.
Sequential Structure
A sequential structure simply means that the instructions are performed one after the
other. This is the default programming structure, and what we have been using so far.
Decision Structure
Decision structures are used whenever the program needs to choose between two or more
sets of instructions. If you find yourself thinking, if x is this, then do that; otherwise, do
this other when you need a decision structure.
There are two basic types of decision structures in C++: if-elseif structures and case
structures.
Lets start with an example:
Line 6 assigns a value of 95 to a variable of data type int. Lines 7 through 10 make up an
if statement. Line 7 asks whether or not the temp is greater than 90. If that is true, the
program continues with line 8 and continues through line 10. It if is not true, the program
continues with line 11. Here is the output:
Lets add a little bit to the program. Lets have a message displayed if the temperature is
not greater than 90.
Lets change the temperature to 60 and see what happens. All we need to do is change
line 6 to int temp = 60;
Lets add some more! If the temperature is greater than 90, Its hot outside. If its less
than 60, its cold. Otherwise, the program will say its nice outside.
Based on our program, with the temp at 60 it should first check to see if it is greater than
90. It isnt, so the program skips down to line 11. Is the temperature less than 60? Not, its
actually equal to 60. The program then skips to line 15. It should display the message on
line 17, then skip down to line 19.
Repetition Structure
Any time a segment of code needs to be repeated until some condition is met, you need a
repetition structure. There are two basic types of repetition structures: those that run a
certain number of times that you can figure out before hand, which would use for
structures, and those that you dont know ahead of time how many times they need to run,
such as while structures. We will look at the while structure first.
To demonstrate the while structure, lets look at an example. We will ask the user to input
a positive integer. As long as the number is less than 1, we will keep asking.
You will notice that we declared a varible num and assigned it an initial value of -1. Next,
we see the while structure. It starts on line 7, and the body of the while structure extends
from line 8 to line 12, between the curly braces { and }. Everything between { and } is
repeated until the value of num becomes greater than or equal to 1. Lets test it out.
The reason we gave num an initial value of -1 is to make sure the loop runs at least one
time. Every time we enter a value less than 1, the loop repeats and asks us for another
value. As soon as we entered a value greater than or equal to 1 (in this case, 2) the loop
ended.
Another repetition structure available in C++ is the for loop. Lets write a loop to find the
sum of all numbers between 1 and 5. We know the answer should be 1 + 2 + 3 + 4 + 5 =
15.
We declare two variables: sum and i. The variable i is our loop counter: we will use it to
keep track of how many times we have executed the loop. To find the sum of 1 through 5
we will need to execute the loop exactly 5 times. Note that sum starts out with a value of
0.
Lines 8 through 11 make up the for structure. The body of the for loop, or the instructions
that need to run each time the loop executes, is between the curly braces { and }. The
body of the loop in this case consists of just one line of code: sum += i.
Now lets look in detail and line 8. Line 8 tells the computer to assign an initial value of 1
to the loop counter i, and keep running the loop until i is greater than 5. Finally, each time
though the loop add 1 to the value of i.
The body of the loop adds the new value of i to the running sum.
Here is the output:
This function is named DemoFunction, and its defined on lines 4 though 7. It returns a
value of data type int. The variables it needs to run are called its arguments, and they are
a and b, both of type integer. Everything between the curly braces { and } constitutes the
body of the function.
Just declaring a function isnt very useful until you use it. This is referred to calling a
function. Lets call our DemoFunction in a main program.
What this snippet of code does is declare two variables of data type integer, x and y, on
line 11. They are assigned values of 5 and 6, respectively. We also declare a variable z of
type int, but dont give it an initial value.
Next, we call DemoFunction on line 13 and assign whatever value it returns to the
variable z. The program looks up the value of x and y, and copies those values into a and
b, respectively. Next, DemoFunction calculates a*b, which in this case is 5*6=30. It
returns the integer value 30. That value is then assigned to z. Heres the output:
Scope of a Variable
When you define a variable inside main, only the other code inside main can access that
variable. The same is true of a function: when you declare a variable inside of a function,
no other functions can access that variable. Even main cannot access a variable that is
declared inside a function. This has to do with the scope of the variables.
If you define a variable outside of main, it has global scope and any other part of your
program can have access to that variable to not only read its value but change it. This is
called global scope.
When you declare a variable inside main, or inside of a function, it can only be accessed
for reading and writing from inside main or inside the function that declared it. This is
called local scope.
Suppose you need to send a value to a function to use. We have already seen that done
using arguments: a copy of whatever is stored in our variable is sent to the function, but
the function cannot change the value of the variable as it exists in the code that called it.
There is a way around this called pointers, but that is an advanced topic.
The definition of the class Triangle can be found on lines 4 through 8, and consists of line
4 and everything between the curly braces { and }. Member variables a and b are setup on
line 5, and assigned the data type integer. Line 6 establishes that the functions that follow
can be accessed by any program using the Triangle class. Lines 7 and 8 tell the compiler
that there will be two member functions connected with the class. The name of the first
one is setValues, and it needs two integer values to accomplish its goal. The word void
means that it does not return a value. The second function is called Area, and it does not
any additional data to do its job. It returns a value of data type float. The end of the class
definition is on line 8. The }; signifies the end.
Lines 9 through 10 define the function that assigns the values to the class member
variables. It needs to integer values as input: the length of each side. These values are
assigned to the member variables a and b.
Lines 12 and 13 define the member function that calculates the area of the triangle.
Because this function belongs to the Triangle class, it has direct access to the values stored
in a and b. It returns the area as data type float.
The main program is in lines 15 through 24. Notice that the variable tri is declared to be
of class Triangle on line 19, just as if it were a built-in data type. When a variable is
based on a class, it is referred to as an object. Line 20 assigns the length of its side, and
line 21 calculates and displays the area.
Here is the output from the function:
If you received value from this book, then Id like to ask you for a favor. Would you be kind enough to leave a review
for this book on Amazon?
*If the links do not work, for whatever reason, you can simply search for these titles on the Amazon website to find
them.