Introduction To C++: Computer Science I
Introduction To C++: Computer Science I
Introduction To C++: Computer Science I
Computer Science I
Quote...
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
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
That
#include <iostream>
int main()
{
int number;
mea
std::cout << “Enter a number”
<< std::endl; ns
std::cin >> number;
std::cout << “You entered: “ << right
now!
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
AB T F
Expression is True T T F
iff A and B are F F F
both true
Logical Operations: Or
AB 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”
AB “A greater than or equal to B”
“A not less than B”
AB “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.
Movie, soda
Movie & soda & popcorn
How about a diagram?
Boxes
Money < $10.50
represent
actions
Movie, soda
Movie & soda & popcorn
How about a diagram?
Diamonds
Money < $10.50
represent
decision
points
Stay home Money < $15.00
Movie, soda
Movie & soda & popcorn
How about a diagram?
Arrows
Money < $10.50
show flow
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
subsequent
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
the individual costs popcorn 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()
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:
and/or
the outcomes are chosen based upon
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?
F What if you
Condition
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
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
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
#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()