An introductory PowerPoint to understanding and applying the C++ programming language. Broken down into lessons covering:
Introduction: Definitions and the History of Programming
Lesson 1: Libraries, Variables and Types, Blocks and Namespaces, Functions
Lesson 2: If...Else Statements, For and While Loops, Scope
Exercise: Program a Gumball Game
Lesson 3: Classes and Objects, Pointers
4. Definitions
• Programming
Language
• A set of operations and values
organized in a language-like structure
that can be created, altered, used, or
destroyed to create a piece of software
that can be used by clients.
• Compiler • A particular piece of software designed
to convert users’ code into a language
that computers can interpret. (Example:
MinGW)
• Integrated
Development
Environment
(IDE)
• A particular piece of software designed
to aid users in writing their code as
well as compiling it. (Example:
Microsoft Visual C++ Express)
5. Definitions (cont.)
• Object-Oriented
Programming(OOP)
• A type of programming and language that
uses classes and objects (explained
later) that is designed to increase
program complexity without increasing
difficulty. (Example: C++)
6. Brief History of C-Programming
• C is a language designed between 1969 and 1973 by
Dennis Ritchie at AT&T Bell Labs. C revolutionized
programming of the time with its syntax and
capabilities, and today is the most widely used
programming language. C inspired languages such as
Java and Python, among others.
• C++ is a language designed in 1983 by Bjarne
Stroustrup, also at AT&T Bell Labs. The origin of the
name is based on “C plus classes”, meaning a
variation of the C language incorporating a class-
object system.
• Another language, C#, was designed by Microsoft in
2000, intended to operate as a more complex version
of C++ with more flexibility and complexity.
8. Libraries
• A library is like a set of variables and functions
that have been pre-coded for general use; one such
example is the library iostream, which allows you to
read and write from and to direct environments (for
example, a player pressing a key and telling the
player what it does) and files (for example, in
saving and loading games.)
• Libraries are generally referenced to – included – at
the top of code files in this way:
#include <library>
• In the later example, “#include <iostream>” will give
us the “cin” and “cout” operations, allowing us to
communicate with the user with input and output.
9. Variables and Types
• A variable is a name that represents a value. For
example, if I wanted to create a variable called
students that held the number of students in a class,
in C++, I’d write something like this:
int students = 18;
• However, something is missing: the variable’s type. A
type tells the computer what kind of value the
variable holds. There are a handful of different
types we will initially use:
int (integer, any number; ex. 2 or 5)
float (any decimal number; ex. 2.2 or 5.5)
char (a character; ex. ‘a’)
bool (boolean, true or false)
10. Variables and Types (cont.)
• Here’s how we correct the previous example:
int students = 18;
• Say a portion of these students have A’s in the
course; arbitrarily, 13. That is 72.2%. In order to
express this number in C++, you have to precede it by
the float type:
float percentWithAnA = 72.2;
• Say this is a science course. How can we represent
what kind of course it is in C++?
bool isScienceClass = true;
bool isHistoryClass = false;
…
11. Blocks, Namespaces, and Labels
• Sections of code can be divided from each other in a
sort of hierarchical structure; for example:
cout << “Hello!”;
{
cout << “Hello2!”;
}
• This fragment will run both cout operations without
any difference from the operations without the
bracket block. Later, when we talk about scope, this
will be a useful tool for separating parts of code
using the same variables.
12. Blocks, Namespaces… (cont.)
• Another useful feature of C++ is namespaces.
Essentially, namespaces allow you to name blocks of
code that operate on their own but can later be
referenced to by other sections; for example:
namespace maths {
float pi = 3.14;
}
cout << maths::pi;
• The above fragment will print “3.14”. The :: sign
indicates a value residing in the namespace.
13. Blocks, Namespaces… (cont.)
• Consider this:
namespace maths {
float pi = 3.14;
}
cout << maths::pi;
void main() {
float pi = 3.1415;
cout << maths::pi;
cout << pi;
}
• The above fragment will print “3.14” twice and then
“3.1415” once; the first two couts refer to the pi in
maths, while the last refers to the pi in main().
14. Blocks, Namespaces… (cont.)
• Remember that cout and cin are operations provided by
the library iostream (#include <iostream>). What I
have not yet shown, however, is that the cout and cin
operations are included in the namespace std, for
standard; to use them properly, they must be preceded
by std::, making them std::cin and std::cout.
• In the beginning of almost all programs (especially
our programs), you will see this line:
using namespace std;
• This is what allows us to use cout and cin without
being preceded by std::.
15. Blocks, Namespaces… (cont.)
• Return to our previous example. Consider this:
namespace maths {
float pi = 3.14;
float tau = 2*pi;
}
using maths::pi;
cout << pi;
cout << maths::tau;
• Because we included the maths::pi variable with the
using identifier, it can be referenced to at any
point after the using clause as, simply, pi. If we
said using namespace maths;, then tau could be used
as well without preceding it with maths::.
16. Blocks, Namespaces… (cont.)
• Labels are another way in which sections of code can
be identified. Labels allow the program to jump to
certain areas to either skip or re-perform
operations; for example:
cout << “I’m going to skip the next cout!” << endl;
goto skipcout; // goto <label>
cout << “This cout is skipped. =(“ << endl;
skipcout: // <label>:
cout << “This cout was not skipped! =D” << endl;
17. Functions
• Functions are the fundamental ways that programs
operate. Functions, also called methods, are invoked,
sometimes with certain variables – identified by
order and type, as below - to perform a task.
• Functions usually return values; because of this, a
function is preceded by the type of the return (and
if the function does not return anything, by void.)
• To model multiplication (though redundant):
int multiply(int a, int b) {
return a*b;
}
• Then, to set variable c to 5 times 6:
int c = multiply(5, 6);
18. Functions (cont.)
• The primary function we will initially work with is the
main() function. It is written in new projects like
this:
void main() {
}
• The main() function does not normally return anything or
take any parameters; it is the default function that is
run when the program is started, and thus can be used to
initialize variable values and run other methods that
get the program in motion. For example:
#include <iostream>
void printStart() {
cout << “Started!”;
}
void main() {
printStart();
}
20. If…Else Statements
• In a previous example, we listed boolean variables
telling the program if a course is a science or
history course:
bool isScienceClass = true;
bool isHistoryClass = false;
• How do we use these variables later? This is where a
fundamental principle of programming in C++ comes in:
If…Else statements:
if (isScienceClass) {
// Load a certain science lesson.
} else {
// Load a certain history lesson.
}
21. If…Else Statements (cont.)
• There is another condition to the example, however; you
can test if it is a science course and then load a
science lesson, or if it isn’t, load a history lesson.
What if there are more than just science and history
courses? What about a math course? For that, we have to
change it to this:
…
bool isMathClass = false;
…
if (isScienceClass) {
// Load a certain science lesson.
} else if (isHistoryClass) {
// Load a certain history lesson.
} else {
// If none of the above, load a math lesson.
}
22. If…Else Statements (cont.)
• There is another way we could write this that allows
us to both test for isMathClass and, if none of the
above, assess that the course subject is unknown.
…
if (isScienceClass) {
// Load a certain science lesson.
} else if (isHistoryClass) {
// Load a certain history lesson.
} else if (isMathClass) {
// Load a certain math lesson.
} else {
// No course subject?
}
23. For and While Loops
• Another fundamental programming concept in C++ is a
loop. There are multiple kinds of loops that operate in
different ways:
for loops are loops that use an int to iterate through,
performing an operation for each iteration, and are written
like this:
for (int i=0; i<x; ++i) {
// Do something like “cout << i;”
}
while loops are loops that use an unknown condition and
iterate for as many times as possible while the condition is
true. There are two ways to write while loops; here is the
primary way:
int i = 0;
while (i<10) {
// Do something like “cout << i;”
++i;
}
24. For and While Loops (cont.)
• Another way to write a while loop is with do…while:
int i = 0;
do {
++i;
} while (i<10);
• The difference between the two formats is that in a
do…while loop, the operation is run at least once.
The “while” condition is evaluated after the
condition is run. In a regular while loop, as
demonstrated previously, the condition is evaluated
before, and if true, then the condition is run. At
the end of the operation, the iteration is performed.
If the condition is not met at the end of a do…while
loop, then the operation is not run again.
25. For and While Loops (cont.)
for (int i=0;i<10;++i) {
// Do something.
}
int i = 0;
while (i<10) {
// Do something.
++i;
}
int i = 0;
do {
// Do something.
++i;
} while (i<10);
Define; condition; iterate
Operation
End
Define
Condition
Operation
Iteration
End
Define
Begin
Operation
Iteration
Condition; End
26. Scope
• Scope is another important concept across all
programming practices. Scope is what allows us to,
for example, use ‘i’ as our iteration variable for
each loop without running into errors.
for (int i=0; i<10; ++i) { /* Operation */ }
• Because i is initialized (created) inside of the for
loop (which includes the condition and the
operation), it can only be used inside the loop. If I
performed the operation, closed the loop, and then
tried to use “cout << i;”, I would throw an error; i
is undefined outside of the loop, and thus it cannot
be used.
27. Scope (cont.)
• However, consider this code fragment:
int i;
for (i=0;i<10;++i) { /* Operation */ }
cout << i;
• The result of the above code would be that the
operation is performed ten times, and then i – 10 –
is printed. This is because i was defined outside of
the loop, and then iterated by it; therefore, because
the last iteration of the loop – i = 9, i < 10, ++i –
results in i becoming 10, the result that is printed
is “10”.
29. Program a Gumball (1/11)
• Let’s put what you’ve learned to the test. To do this,
we will program a Gumball, or a number-guessing game
similar to the raffle game where you have to guess the
number of gumballs in the machine.
• How will we do this? First and foremost, we need to
create our project. In MVC++, create a new CLR Empty
Project from the New Project menu. At the bottom, enter
the name of your project in the first input box as
“Gumball”, and create the project.
• MVC++ will now give you the basic structure necessary to
begin making your project. In order to get programming,
however, you need to create a .cpp, or C++, code file.
Click on “Add New Item” in the top left, select “C++
File (.cpp)”, name it “main”, and click Add.
30. Program a Gumball (2/11)
• We now have an empty code document to begin working
on. Let’s start from the beginning with the
libraries. For this example, we’ll need two
libraries: iostream and ctime.
#include <iostream>
#include <ctime>
• The uses of these libraries will be explained as we
go along.
• As previously mentioned, cout and cin use std::, so
for ease of use, let’s add “using namespace std;”
after our #includes:
using namespace std;
31. Program a Gumball (3/11)
• In order for our Gumball game to generate a random
number each time the program is run, we have to use
the std::rand() operation. rand() (given the using
namespace std;) is used like so:
int x = rand()%max +1;
• …where max is the largest number you want rand() to
generate minus one (since, to avoid generating a 0,
the one is added along with rand().)
• rand() essentially returns a number within the range
of 0 to max based on a list of numbers defined in
C++. Because the random sequence is absolute, meaning
it does not change each time the program is run, we
must add another operation in order to truly
randomize it.
32. Program a Gumball (4/11)
• The srand() operation provides rand() with a seed;
this means that each time the program is run, so long
as srand() is used before a random number is
generated with a unique number inside the
parentheses, rand() will generate different numbers
each time.
• In order to provide srand() with its own unique
number, the most convenient way to do this – and why
we included the ctime library – is using the current
time, like this:
srand((unsigned)time(0));
• unsigned will be explained later on.
33. Program a Gumball (5/11)
• Now that we know how to generate truly random numers
each time the program is run, we can write this:
void main() {
srand((unsigned)time(0));
int theNumber = rand()%100 +1;
int guesses = 10;
int guess;
}
• Here, theNumber is the number of hypothetical
gumballs in the machine; the number the player is
trying to guess. guesses is how many tries the player
has. guess is the player’s current guess. Now, we
need to exploit our while loops:
while (guesses>0) { }
34. Program a Gumball (6/11)
• What do we want to do while the player still has
guesses? Let the player guess, of course!
• How does the player know what to do? Well, let’s tell
them:
cout << “Guess a number: “;
• Notice that we only printed out one string; we didn’t
“end the line”, and therefore, whatever comes next
(in the console) will be on the same line. If we
wanted to end the line, we’d add n inside the quotes
at the end of everything else, or add “ << endl;”
after the quotes instead of “;”.
35. Program a Gumball (7/11)
• Now, of course, the player guesses:
cin >> guess;
• For the purpose of this example, we’ll assume the
player correctly enters an integer; normally, if the
player entered a value of a different type, we would
get errors.
• Instead, let’s move on. Is the player correct?
if (guess == theNumber) { }
• The == operator means “is equal to”, and will return
either false or true whether or not the left value is
equal to the right.
36. Program a Gumball (8/11)
• If the player’s guess is indeed equal to theNumber,
then we’ll want to close the while loop so that the
player doesn’t have to guess again. We can do that
using “break;” after telling the player they’ve won:
cout << endl << “You win!”;
break;
• However, what if they player isn’t correct?
if (guess == theNumber) {
cout << endl << “You win!”;
break;
} else {
}
37. Program a Gumball (9/11)
• Did the player guess a number higher or lower than
theNumber?
if (guess > theNumber) {
} else {
}
• What do we want to happen in either case?
cout << “Too high!” << endl;
…
cout << endl << “Too low!” << endl;
• Of course, in either case, the player is wrong, and
they have used one guess:
--guesses;
38. Program a Gumball (10/11)
• The while loop we wrote continues until guesses is no
longer greater than 0, and if the player was correct,
it exits; therefore, if the player has reached 0
guesses, they have not gotten it correct. We can test
for this after --guesses; like this:
--guesses;
if (guesses == 0) {
cout << endl << “Game over!”;
}
• Since the loop will then exit, we do not need break;,
however, we should probably just tell the player what
the number was:
cout << endl << “The number was: “ << theNumber << endl;
39. Program a Gumball (11/11)
• One small feature we will use to end this program is
one that stops the program from exiting, given that
it has finished all of its operation. After all of
the present code, add this line:
system (“pause”);
• This line will force the console to enter a paused
state, meaning that it will not continue exiting code
until the user hits a key. This will allow the player
to see the final message – “The number was: …” – and
then exit on their own will.
• Click the green “Start Debugging” arrow at the top.
If your code looks like the following, your program
should run flawlessly; if your code is flawed, you
may get errors.
40. #include <iostream>
#include <ctime>
using namespace std;
void main() {
srand((unsigned)time(0));
int theNumber = rand()%100 +1;
int guesses = 10;
int guess;
while (guesses>0) {
cout << “Guess a number: “;
cin >> guess;
if (guess == theNumber) {
cout << endl << “You win!”;
break;
} else {
if (guess > theNumber) {
cout << “Too high!” << endl;
} else {
cout << “Too low!” << endl;
}
--guesses;
}
if (guesses == 0) {
cout << endl << “Game over!”;
}
}
cout << endl << “The number was: “ << theNumber << endl;
system (“pause”);
}
42. Classes and Objects
• Classes and objects are the primary structures and
the benefits of using Object-Oriented Programming, as
they provide the capability of mimicking real-world
things. For example: shapes have areas and
perimeters. Shapes can be represented by a class.
Shapes
area, perimeter
43. Classes and Objects (cont.)
• One kind of shape is a rectangle. This, too, can be
represented by a class that is a shape, therefore
making it a subclass. Rectangles also have length and
width. (For the presentation, values or functions
that are inherited from a parent class, or class upon
which another class is based, are preceded by ^.)
Shapes
Rectangles
length, width
^area = length*width
^perimeter = 2*length + 2*width
44. Classes and Objects (cont.)
• One kind of rectangle is a square. A square has equal width
and height. Therefore, a square can be a subclass of
rectangle where width and height are the same.
Shapes
Rectangles
Squares
^length, ^width; length = width,
^^area = length*length = width*width, ^^perimeter = 4*width = 4*length
45. Classes and Objects (cont.)
• Not all shapes have the same height and width; not all
rectangles have the same height and width; not all squares
have the same height and width. Therefore, classes
represent, in effect, templates. Objects are things created
based on these templates; for example, let’s create two
squares:
Squares
length, width
length = width
area = length*length = width*width
perimeter = 4*width = 4*length
Square a
length = width = 10
area = length*length = width*width = 100
perimeter = 4*width = 4*length = 40
Square b
length = width = 20
area = length*length = width*width = 400
perimeter = 4*width = 4*length = 80
46. Classes and Objects (cont.)
• Another type of shape is a circle.
Shapes
Circles
radius, circumference
diameter = 2*radius
^area = 3.14*radius*radius
^perimeter = circumference = 2*3.14*radius = diameter*3.14
47. Classes and Objects (cont.)
• This is now the hierarchy of our classes:
Shapes
CirclesRectangles
Squares
48. Classes and Objects (cont.)
• Let’s create a circle along with our squares:
Square a
Square b
Circles
Circle c
radius = 5
diameter = 2*radius = 10
area = 3.14*radius*radius = 78.5
perimeter = 2*3.14*radius = diameter*3.14 = 31.4
49. Classes and Objects (cont.)
• We can create a regular rectangle, too:
Square a
Square b
Rectangles
Circle c length = 5
width = 10
area = length*width = 50
perimeter = 2*(length+width) = 30
Rectangle d
50. Classes and Objects (cont.)
• We now have two squares, a circle, and a rectangle;
in other words, we have three rectangles and a
circle; otherwise, we have four shapes. We could
create more if we wanted to. We could, if we wanted
to, create a Shape that is neither a rectangle,
square, or circle, only possessing an area and
perimeter.
Square a
Shape eCircle c Rectangle d
Shapes
area = 92.67
perimeter = 58.3
Square b
51. Pointers
• Pointers are a difficult concept to explain. In order
to show you how they work, I will just give you this
fragment:
int a = 10;
int b = a;
int *c = &a;
cout << a;
cout << b;
*c = 5;
cout << a;
cout << b;
• This is what is printed out: 10, 10, 5, 10.
52. Pointers (cont.)
• This works the way it does because pointers allow you
to use variables as references to other variables.
Instead of setting c to the value of a, we set it,
literally, to a; therefore, when *c (read as “the
value of c”) is changed, it is really changing the
value of a, whereas b was set to the value of a, and
therefore it does not change when a is changed.
a
10 b
10
c
a
*c references to the value of c, or a.
*c = 5, therefore, means a = 5.
b = a, therefore, means b = 10, not a.
53. Pointers (cont.)
• Here is a good use of pointers:
void change(int *target, int value) {
*target = value;
}
…
int x = 10;
int *y = &x; // value of y is at location of x
change(y, 5);
cout << x;
• The output: 5. The value of x is changed when y is
used in the change() function.
*target
y
y
&x
x
10