Anda di halaman 1dari 118

Introduction to C++

Computer Science I
Quote...

 “Language is the only


instrument of science….”
 Samuel Johnson
Q: What is C++
 C++ is a compiled, object-oriented language
 It is the “successor” to C, a procedural
language
 (the “++” is called the successor operator in C++)
 C was derived from a language called B which
was in turn derived from BCPL
 C was developed in the 1970’s by Dennis
Ritchie of AT&T Bell Labs
 C++ was developed in the early 1980’s by
Bjarne Stroustrup of AT&T Bell Labs.
 Most of C is a subset of C++
Compiling C++
Use gcc, Visual Studio, Dev Cpp etc.

File types
.cc, .cp, .cpp, .CPP, .cxx, .c++, .C
.h, .H
People & Programs
 User: an individual who runs, or
executes, a program
 Programmer: an individual who creates,
or writes, a program
C++ Program
Consists of…
 Declarations
 Define the use of various identifiers, thus
creating the elements used by the program
(computer)
 Statements
 Or executable statements, representing
actions the computer will take on the user’s
behalf
Identifiers
 Names for various entities used in a program;
used for...
 Variables: values that can change frequently
 Constants: values that never changes
 Functions: programming units that represents
complex operations
 Parameters: values that change infrequently
Variable declarations
Meaning: variable <variable-name> will be a variable of type
<type>

Where type can be:


int //integer
double //real number
char //character

Example:
int a, b, c;
double x;
int sum;
char my_char;
Data Types
INTEGER DATA TYPES
name Memory(storage in byte) Range of values
int 4 -2147483648 to 2147483647
short 2 -32768 to 32767
bool 1 True or false
char 1 -128 to 127

FLOAT DATA TYPES


name Memory(storage in byte) Range of values
float 4 -3.4E+38 to 3.4E+38
double 8 -1.7E+308 to 1.7E+308
Escape Sequences
Escape Sequences
\n New line Cursor moves to the beginning of the next line
\t Tab Cursor moves to the next tab stop
\b Backspace Cursor moves one step to the left
\r Return Cursor moves to the beginning of the current line
\\ Backslash Backslash is printed
C++ Comments
Comments are explanatory notes; they are ignored by
the compiler.
There are two ways to include comments in a program:

// A double slash marks the start of


a //single line comment.

/* A slash followed by an asterisk


marks the start of a multiple line
comment. It ends with an asterisk
followed by a slash. */
Simple C++ Program
#include <iostream>  Compiler
directive:
int main() Tells the
{ compiler
// Declarations what to do
// Statements
before
compiling
return 0;
 This one
}
includes
source code
from another
file
C++ Compiler Directives
The #include directive tells the compiler to include some
already existing C++ code in your program.

The included file is then linked with the program.

There are two forms of #include statements:


#include <iostream> //for pre-defined files

#include "my_lib.h" //for user-defined


files
C++ Standard Library Header files
C++ Standard
Library header Explanation
files
<iostream> Contains function prototypes for the C++ standard input and
standard output functions. This header file replaces header file
<iostream.h>. This header is discussed in detail in
Chapter 26, Stream Input/Output.
<iomanip> Contains function prototypes for stream manipulators that format
streams of data. This header file replaces header file
<iomanip.h>. This header is used in Chapter 26, Stream
Input/Output.
<cmath> Contains function prototypes for math library functions. This
header file replaces header file <math.h>.
<cstdlib> Contains function prototypes for conversions of numbers to text,
text to numbers, memory allocation, random numbers and various
other utility functions. This header file replaces header file
<stdlib>.
<ctime> Contains function prototypes and types for manipulating the time
and date. This header file replaces header file <time.h>.
<vector>, These header files contain classes that implement the C++
<list> Standard Library containers. Containers store data during a
<deque>, program’s execution.
<queue>,
<stack>,
<map>,
<set>,
<bitset>
Simple C++ Program
#include <iostream>  Main function

int main()
{
// Declarations
// Statements
return 0;
}
Simple C++ Program
#include <iostream>  Header for
main function
int main()  States…
{  data type
// Declarations for the
return value
// Statements
 identifier for
return 0; function
}  list of
arguments
between
parenthesis
(none for
this
function)
Simple C++ Program
#include <iostream>  Braces
enclose the
int main() body of the
{ function
// Declarations
 They
// Statements
represent the
return 0;
start and end
}
of the
function
Simple C++ Program
#include <iostream>  Declarations
and
int main() statements
{
 Main body of
// Declarations
function (or
// Statements
main part)
return 0;
 “//”
}
represents
the start of a
comment
Simple C++ Program
#include <iostream>  Return
statement
int main()  specifies the
{ value the
// Declarations function
// Statements returns
return 0;  All (almost)
} declarations
and
statements
end with a
semi-colon
“;”
Simple C++ Program
This
#include <iostream>

int main() program
{
// Declarations
doesn’t
// Statements do
return 0;
}
anything
!
Sample C++ Program
#include <iostream>  Variable
declaration
int main()
 The identifier
{ number is
int number;
declared as
std::cout << “Enter a number”
being of data
<< std::endl;
type int, or
std::cin >> number;
integer
std::cout << “You entered: “ <<
number << std::endl;
return 0;
}
Sample C++ Program
#include <iostream>  cout
the output
int main() statement for
{ C++
int number;  Note the
std::cout << “Enter a number” direction of
<< std::endl; “<<“
std::cin >> number;  endl
std::cout << “You entered: “ << represents an
number << std::endl; end-of-line
return 0;
}
Sample C++ Program
#include <iostream>  cin
the input
int main() statement for
{ C++
int number;
 Note the
std::cout << “Enter a number”
direction of
<< std::endl;
“>>”
std::cin >> number;
std::cout << “You entered: “ <<
number << std::endl;
return 0;
}
Sample C++ Program
#include <iostream>  Did you
copy this
int main() down?
{
int number;
 You had
std::cout << “Enter a number”
better,
<< std::endl; since this
std::cin >> number; will be the
std::cout << “You entered: “ << first
number << std::endl; program
return 0; you’ll try!
}
Sample C++ Program
That
#include <iostream>

mea
int main()
{

ns
int number;
std::cout << “Enter a number”

right
<< std::endl;
std::cin >> number;

now!
std::cout << “You entered: “ <<
number << std::endl;
return 0;
}
After you write a C++ program you compile it;
that is, you run a program called compiler
that checks whether the program follows the
C++ syntax
if it finds errors, it lists them
If there are no errors, it translates the C++
program into a program in machine
language which you can execute
Programming style
• In order to improve the readability of your program, use the
following conventions:
• Start the program with a header that tells what the program
does.
• Use meaningful variable names.
• Document each variable declaration with a comment telling
what the variable is used for.
• Place each executable statement on a single line.
• A segment of code is a sequence of executable statements that
belong together.
• Use blank lines to separate different segments of code.
• Document each segment of code with a comment telling
what the segment does.
Assignment
 Assignment is an operation that assigns
the value of an expression to a variable
 Ex.
Total = 2 + 3 + 5
 First, the expresssion “2 + 3 + 5” is
evaluated
 Then, this value is assigned to the
variable “Total”
Assignment
 When a variable is declared, space is
allocated in the computer’s memory for the
variable
 Each data type requires a different number of
bytes in memory for storing a variable
int - 2
float - 4
double - 8
char, bool - 1
Assignment
 When a variable is
Total = 2 + 3 + 5;
assigned a value,
the value is placed
into the variable’s
memory location
Total
10
Arithmetic Operations
 Addition: 2 + 3
 Subtraction: 5 - 2
 Multiplication: 10 * 4
 Division: 12 / 3
Order of Operations
 Arithmetic expressions are evaluated
according to the following order of
operations
 At each level, operations are evaluated
left to right
 (1) Parenthesis, Functions
(2) Multiplication, Division
(3) Addition, Subtraction
Parenthesis
 Parenthesis are used to alter the order
with which operations are evaluated
 Ex.
4 + 5 * 2 equals 14
(4 + 5) * 2 equals 18
Boolean Conditions
 Are built using…
Comparison operators
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

Boolean operators
&& and
|| or
! not
Here we go!
 Problem: To determine the average of three
numbers
 Task: Request, from the user, three numbers,
compute the average and the three numbers,
and print out the original values and the
computed average
 Do it!
 You have 20 minutes!
Computer Science I

Functions
Q: What is a function?
 A programming unit
 Similar to mathematical functions
 Example:
 f(x) = x2 + 5x + 7
 For x = 2, f(2) = (2)2 =5(2) + 7 = 21
Q: What is a function?
 It has...
 ... arguments

 ... a name
(identifier)
 ... a value it
returns
 ... a body int foo(int x)
{
int result;
result = x*x + 5*x + 7;
return result;
}
Procedural Abstraction
 Think “Black Box” !
 When using a function, you only need
to be concerned with what it does, not
how it does it
 When writing a function, you need to
be concerned with the how
Example: Cube it!
int cubeIt(int x) int cubeIt(int x)
{ {
int result; int result;
result = x*x*x; result = x;
return result; result = x*result;
} result = x*result;
return result;
}
Pseudocode
 Looks like a programming language
 Has all the structure of a programming
language
 Has a verrrrrry loose syntax
Pseudocode
 Example:
function foo (x)
result  x2 + 5x + 7
return result
 That’s it!
 Sloppy, ain’t it?
Computer Science I

Decision Statements
Q: What is a decision?
 Something that represents a branching
point in a solution
 Outcomes are often dependent on initial
conditions
Decisions in Programs
 Without decision statements (or other
dynamic control structures), programs
are static
 Static programs do exactly the same
things each time they are executed
 Dynamic programs do not
Control Structure
 Sequence
 Decision
 Iteration (Looping)
Decision Structure
 Simple If
 If then Else
 If ElseIf Else…
 Ladderize
 Nested
Simple If Structure
if (condition)
{
statement1 …n
}
If Else Structure
if (condition)
{
statement1 …n
}
else
{
statement 1 …n
}
If.. ElseIf.. Else Structure
if (condition)
{
statement1 …n
}
else if (condition)
{
statement 1 …n
}
else
{
statement 1 … n
}
Ladderized If and If Else
if (condition) if (condition)
{ {
statement1 …n statement1 …n
} }
if (condition) else
{ {
statement1 …n statement 1 …
} }
if (condition)
{ if (condition)
statement1 …n {
} statement1 …n
if (condition) }
{ else
statement1 …n {
} statement 1 …
}
Ladderized If ElseIf Else
if (condition)
{
statement1 …n
}
else if (condition)
{
statement 1 …n
}
Else if (condition)
{
statement 1 …n
}

else
{
statement 1 … n
}
Nested If ElseIf Else
if (condition)
{
{
statement1 …n
}
if (condition)
{
statement1 …n
}
else if (condition)
{
statement1…n
}
else if (condition)
{
statement1…n
}
else
{
statement1 …n

}
}
Boolean Algebra
 Based on values that are either True or
False
 True and False values are often
represented by 1’s and 0’s, respectively
Logical Operations: And
 AB T F
 Expression is True T T F
iff A and B are F F F
both true
Logical Operations: Or
 AB T F
 Expression is True T T T
if either A or B are F T F
True
 Note: Also True
when A and B are
both True
Logical Operations: Exercises
A = True, B = True, C = False
1. A  B
2. A  C
3. A  B  C
4. (A  B)  (A  C)
Relational Operations
 A <B “A less than B”
 A >B “A greater than B”
 A =B “A equal to B”
 A B “A less than or equal to B”
“A not greater than B”
 AB “A greater than or equal to B”
“A not less than B”
 AB “A not equal to B”
“A less than or greater than B”
Relational Operations:
Exercises
A = 5, B = 3, C = -7
1. A < B
2. A  C
3. (A < C)  (B < C)
Boolean Operations: C++
 AB  A && B
 AB  A ||B
 A<B  A <B
 A>B  A >B
 A=B  A ==B
 AB  A >=B
 AB  A <=B
 AB  A <>B
Try this!
Problem:
 You’d like to go see a movie.

 The movie costs $8.00, a soda costs $2.50


and a large popcorn costs $4.50.
 Based on the amount of money in your
pocket, determine whether you could...
(a) See the movie and buy a soda,
(b) See the movie, and buy soda and
popcorn, or
(c) Stay home
Know?
 Movie costs $8.00
 Soda costs $2.50
 Popcorn costs $4.50
 How much money I have in my pocket
Need?
 Cost of movie and soda
 Cost of movie, soda and popcorn
 Way to select one of the three options
(that is, make a decision!)
Do?
 Option (a) costs $10.50
 Option (b) costs $15.00
 Option (c) costs nothing
 What next?
How about a diagram?
 This is
called a Money < $10.50

flowchart

Stay home Money < $15.00

Movie, soda
Movie & soda & popcorn
How about a diagram?
 Boxes
represent Money < $10.50

actions

Stay home Money < $15.00

Movie, soda
Movie & soda & popcorn
How about a diagram?
 Diamonds
represent Money < $10.50

decision
points
Stay home Money < $15.00

Movie, soda
Movie & soda & popcorn
How about a diagram?
 Arrows
show flow Money < $10.50

Stay home Money < $15.00

Movie, soda
Movie & soda & popcorn
How about a diagram?
 The arrow
at the top Money < $10.50
tells us
there were
previous
steps Stay home Money < $15.00

 The arrow
at the
bottom Movie, soda
tells us Movie & soda & popcorn
there are
subsequen
t steps
How would I write this?
 Using Pseudocode
 Wait!
 What the CENSORED is Pseudocode?
Pseudocode
 Looks like a programming language
 Has all the structure of a programming
language
 Has a verrrrrry loose syntax
Pseudocode
 Example:
get x
result <- x2 + 5x + 7
print result
 That’s it!
 Sloppy, ain’t it?
One more time!
 Pseudocode...
If (Money < $10.50) then
Stay home
else If (Money < $15.00) then
Movie, soda
else Movie, soda, popcorn
How would I write this?
 First, we need to decide how to
organize our solution
 Should we “hard code” the costs of the
movie, soda and popcorn into the
algorithm?
 Should we input these values?
 Let’s take another look at that problem!
How would I write this?
Problem:
 The problem  You’d like to go see a movie.
statement tells us  The movie costs $8.00, a soda
costs $2.50 and a large popcorn
the individual costs costs $4.50.
 Based on the amount of money
 So, let’s assume in your pocket, determine
they’re fixed or whether you could...
constant (a) See the movie and buy a
soda,
 No need to ask the (b) See the movie, and buy
user for them soda and popcorn, or
(c) Stay home
How would I write this?
 Another question: Should we pre-compute
the cost of each option?
 Or, should we let the program do this?
 Since we’ve already stated that the item costs
are fixed, it would seem logical to pre-
compute the cost of each option
 Movie: $8.00
 Movie & soda: $10.50
 All three: $15.00
How would I write this?
 Next, we need to make sure we have a
complete algorithm
Input Money
If (Money < $10.50) then
Display “Stay home.”
else If (Money < $15.00) then
Display “Go to a movie;buy a soda.”
else Display “Go to a movie; buy a
soda and
popcorn.”

 Almost done!
How would I write this?
 Determine how we wish to organize our
program
 Do we want one function?
 Or, should we create a few functions?
 Let’s two functions: One to input Money
from the user
 And a second to determine the outcome
How would I write this?
 Here’s the prototypes for the functions

int getMoney()

void showResults(int myMoney)


Program
 Okay, now we get to use our algorithm
and program design to create a
program
 Well, what are you waiting for?

Do It!!!
Multiway Branching
 If statements can be used for multiway
branching
 That is, choosing one of n mutually
exclusive outcomes
 But what about n outcomes that are not
totally unique?
Multiway Branching
 Consider the following problem:

Each year, a local middle school


requires students to purchase supplies
based on their grade level. 6th graders
need pencils and five notebooks. 7th
graders also need a calculator. 8th
graders add to this a 3-ring binder with
loose leaf paper.
Multiway Branching
 We could use a nested If statement to handle
this, but there is an alternative
 Whenever we need to represent a decision
step, with n possible outcomes, where
 the outcomes form subsets of each other,
and/or
 the outcomes are chosen based upon
unique scalar values for a control
expression,
 we can use a Case (switch) structure
Multiway Branching
 Case
When Grade = 8th
3-ring binder
loose leaf paper
When Grade = 7th
calculator
When Grade = 6th
pencils
5 notebooks
Multiway Branching
 In C++ ...
switch (grade){
case 8:
cout << “3-ring binder, loose leaf, “;
case 7:
cout << “calculator, “;
case 6:
cout << “5 notebooks, & pencils.” << endl;
}
 When the switch is encountered, control jumps to the
matching case statement and continues until either a break is
found or the end of the switch
Multiway Branching
 Here’s an example with a few break’s
cout << “Your lunch period comes “;
switch (grade) {
case 8:
cout << “first.” << endl;
break;
case 7:
cout << “second.” << endl;
break;
case 6:
cout << “third.” << endl;
} No final break
Exercise:
 Create a program that will inform the
user which advisor they should go to
based on their major code number

Well? Get started!


Computer Science I

Loops
Q: What is a Loop?
 A control structure that allows for a
sequence of steps to be repeated a
certain number of times
 This sequence of steps is called the
body of the loop
Q: What is a Loop?
 There are three basic loop structures in
programming:
 For
 While
 Repeat
While loop
Look familiar?

Condition
F
What if you
added a change
T step to the end
of the body?
Body
For loop

F
Condition

Body
While loop
A while loop is
F a control
Condition
structure where
T
the body is
repeated as long
as the condition
Body is true
While loop
When the
F condition is
Condition
false, the body
T
is bypassed, and
flow continues
with the next
Body part of the
algorithm
Example: Sequential search
k  0
found  False
while (k<size)  (found)
F do if A[k] = target
(k<size)  (found)
then found 
True
T else k = k +
1

if A[k] = target
then found  True
else k = k + 1
Example: Sequential search
k = 0;
found = False;
while ((k<size) &&
F (!found))
(k<size)  (found) if (A[k] == target)
found = True;
T else k = k +
1;

if A[k] = target
then found  True
else k = k + 1
Exercise
 Strings are arrays of characters
 How would you determine if a string
fragment is part of a larger string?
(needle in a haystack?)
Computer Science I

Arrays
Q: What is an array?
 An array is a data structure consisting
of one or more indexed members
 An array is like a row of mailboxes at
the post office
 Each box is numbered in sequence
(indices), and …
 Each box contains the same type of
stuff (datatype)
An array could be drawn like

g d a f c z l
0 1 2 3 4 5 6
An array could be drawn like

g d a f c z l
0 1 2 3 4 5 6

Each box is numbered in sequence


An array could be drawn like

Each box has the same datatype

g d a f c z l
0 1 2 3 4 5 6
In pseudocode we use …
 X[j]
 Where X is the name of the array
(identifier), and …
 j is an index indicating which position
in the array we wish to address
An array is declared by …
int X[10];
 Where int is the common datatype for all

elements in the array,


 X is the name of the array (identifier), and …

 10 is the size of the array, or how many

elements are in the array


 Indices for a C++ array always begin with 0
Example: Student Grades
// Declare array
double stGrades[7];
:
// Assign value to array element
stGrades[5] = 87;
:
// Display array element
cout << stGrades[3] << endl;
Problem:
 Create a program that will ask the user
for three (3) numbers, determine the
average, and then display the original
numbers and the average
 Hint: You might wish to use a loop as
well as an array!
Computer Science I

Strings
What is a string?
 A string is a sequence of characters
 Example:
nc9*hNB98B&^v*&G
 Blank spaces are characters
 Each character requires one byte of storage
in memory
 Each character is represented by a one byte
character code, usually an ASCII code
Strings
 A literal is a string bounded by
quotation marks
 Example:
“nc9*hNB 98B&^v*&G”
 Notice the blanks spaces in the
sequence - they are characters!
Strings
 In C++, we declare string variables as
follows
 char string_identifier[length];
 string_identifier is the name of the
string variable
 length represents the length of the
string, or how many characters are in
the sequence
Strings
 Example:
void main()
{
char name[24];
cout << “Enter your name: “;
cin >> name;
cout << “Your name is “ << name <<
endl;
}
Streams
A stream …
 Is a flow of characters
 Is an object that represents either on input
or an output to a program
 Can be associated with the keyboard,
monitor, or files
 cout is an output stream
 cin is an input stream
How about file I/O?
Where definitions for
#include <fstream.h> datatypes ifstream
: and ofstream are
ifstream in_stream; located
ofstream out_stream;
:
Input stream declaration

Output stream declaration


How about file I/O?
#include <fstream.h>
: Associates files
ifstream in_stream; with streams &
ofstream out_stream; opens files for
: use
in_stream.open(“infile.txt”);
out_stream.open(“outfile.txt”);
instream >> number; Stream use
outstream << number << endl;
instream.close();
outstream.close(); Closes files
:
What if a file doesn’t exist?
In_stream.open(“notthere.txt”);
If (in_stream.fail())
{
cout << “Input file opening failed” << endl;
exit(1);
}
How about formatting?
out_stream.setf(ios::fixed);
out_stream.setf(ios::showpoint);
out_stream.precision(2);
Set flag:
out_stream.width(10); fixed/scientific
: showpoint
showpos
Number of digits right/left

Number of
decimal places
More member functions
 get()
 put()
 eof()

Anda mungkin juga menyukai