SlideShare ist ein Scribd-Unternehmen logo
1 von 53
What is C++?
An Introduction to General Programming and
Programming with C++
Overview
1. Introduction
1. Definitions
2. Brief History of C-
Programming
2. Lesson 1
1. Libraries
2. Variables and Types
3. Blocks, Namespaces, and
Labels
4. Functions
1. Lesson 2
1. If…Else Statements
2. For and While Loops
3. Scope
2. Exercise 1
1. Program a Gumball
3. Lesson 3
1. Classes and Objects
2. Pointers
Introduction
• Definitions
• Brief History of C-Programming
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)
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++)
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.
Lesson 1
• Libraries
• Variables and Types
• Blocks and Namespaces
• Functions
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.
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)
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;
…
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.
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.
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().
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::.
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::.
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;
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);
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();
}
Lesson 2
• If..Else Statements
• For and While Loops
• Scope
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.
}
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.
}
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?
}
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;
}
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.
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
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.
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”.
Exercise 1
• Program a Gumball
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.
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;
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.
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.
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) { }
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 “;”.
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.
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 {
}
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;
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;
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.
#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”);
}
Lesson 3
• Classes and Objects
• Pointers
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
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
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
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
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
Classes and Objects (cont.)
• This is now the hierarchy of our classes:
Shapes
CirclesRectangles
Squares
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
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
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
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.
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.
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

Weitere ähnliche Inhalte

Was ist angesagt?

C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsStephane Gleizes
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Ali Aminian
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 

Was ist angesagt? (20)

C++ theory
C++ theoryC++ theory
C++ theory
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
C++11
C++11C++11
C++11
 
Modern C++
Modern C++Modern C++
Modern C++
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
C++
C++C++
C++
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
C
CC
C
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
C tutorial
C tutorialC tutorial
C tutorial
 

Andere mochten auch

Boostのあるプログラミング生活
Boostのあるプログラミング生活Boostのあるプログラミング生活
Boostのあるプログラミング生活Akira Takahashi
 
闇魔術を触ってみた
闇魔術を触ってみた闇魔術を触ってみた
闇魔術を触ってみたSatoshi Sato
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
C++ Template Meta Programming の紹介@社内勉強会
C++ Template Meta Programming の紹介@社内勉強会C++ Template Meta Programming の紹介@社内勉強会
C++ Template Meta Programming の紹介@社内勉強会Akihiko Matuura
 
Template Meta Programming入門から応用まで
Template Meta Programming入門から応用までTemplate Meta Programming入門から応用まで
Template Meta Programming入門から応用までyoshihikoozaki5
 
ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14Ryo Suzuki
 

Andere mochten auch (8)

Boostのあるプログラミング生活
Boostのあるプログラミング生活Boostのあるプログラミング生活
Boostのあるプログラミング生活
 
闇魔術を触ってみた
闇魔術を触ってみた闇魔術を触ってみた
闇魔術を触ってみた
 
C++14 Overview
C++14 OverviewC++14 Overview
C++14 Overview
 
C++の黒魔術
C++の黒魔術C++の黒魔術
C++の黒魔術
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
C++ Template Meta Programming の紹介@社内勉強会
C++ Template Meta Programming の紹介@社内勉強会C++ Template Meta Programming の紹介@社内勉強会
C++ Template Meta Programming の紹介@社内勉強会
 
Template Meta Programming入門から応用まで
Template Meta Programming入門から応用までTemplate Meta Programming入門から応用まで
Template Meta Programming入門から応用まで
 
ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14
 

Ähnlich wie C++ Presentation

Programming Language
Programming  LanguageProgramming  Language
Programming LanguageAdeel Hamid
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointersTAlha MAlik
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.pptDevliNeeraj
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++Amresh Raj
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 

Ähnlich wie C++ Presentation (20)

Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Return of c++
Return of c++Return of c++
Return of c++
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
2CPP02 - C++ Primer
2CPP02 - C++ Primer2CPP02 - C++ Primer
2CPP02 - C++ Primer
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
L6
L6L6
L6
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
 

Kürzlich hochgeladen

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Kürzlich hochgeladen (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

C++ Presentation

  • 1. What is C++? An Introduction to General Programming and Programming with C++
  • 2. Overview 1. Introduction 1. Definitions 2. Brief History of C- Programming 2. Lesson 1 1. Libraries 2. Variables and Types 3. Blocks, Namespaces, and Labels 4. Functions 1. Lesson 2 1. If…Else Statements 2. For and While Loops 3. Scope 2. Exercise 1 1. Program a Gumball 3. Lesson 3 1. Classes and Objects 2. Pointers
  • 3. Introduction • Definitions • Brief History of C-Programming
  • 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.
  • 7. Lesson 1 • Libraries • Variables and Types • Blocks and Namespaces • Functions
  • 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(); }
  • 19. Lesson 2 • If..Else Statements • For and While Loops • Scope
  • 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”); }
  • 41. Lesson 3 • Classes and Objects • Pointers
  • 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