cs31day9 Wk 4 W lecture slides

cs31day9 Wk 4 W lecture slides -...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Substitute:
Brian
Choi
   Type
bool
   More
on
functions
   Parameter
passing
by
value
vs.
by
reference
   How
to
evaluate
functions
   Project
3
Clarification,
Q&A
   Expressions
that
evaluate
to
either
true
or
 false
   age >= 21   weight > 100 && weight < 200   name == “egg” && cost < 15   There
is
a
data
type
whose
only
values
are
 true
and
false.
   Use
bool
to
store
true
or
false
values.
   bool canDrink = (age >= 21);   bool shouldBuy = (name == “egg” && cost < 15);   C++
defines
two
constants
true
and
false,
 which
you
can
directly
assign
to
a
bool.
   bool aceMidterm = true;   bool flunkTheCourse = false;   A
simple
example:
 int age; cout << “Enter your age: ”; cin >> age; bool canDrink = (age >= 21); if (canDrink) cout << “You can drink!” << endl; else cout << “Stay away!” << endl; int sum(int begin, int end) { int temp = 0; for (int i = begin; i <= end; i++)arguments/parameters
 inputs
into
a
function,
 { which
are
used
to
 temp += i; determine
the
result
 } return temp; function
name
 } Same
rules
as
variable
 return
value
 the
result
of
the
 function
call
 The
type
of
it
must
 be
compatible
to
the
 return
value.
 identifiers
apply.
 return
type
 data
type
of
the
 result,
or
the
 “return
value”
 Computes
the
sum
 of
numbers
begin
 to
end.
   Boolean
functions
are
functions
whose
return
 type
is
bool.
   It
is
like
asking:
given
a
set
of
arguments,
is
a
 certain
condition
met?
 cout << “Enter a phone number: ”; string t; getline(cin, t); int numberOfDigits = 0; for (int k = 0; k != t.size(); k++) { if (isdigit(t.at(k))) numberOfDigits++; } if (numberOfDigits != 10) cout << “A phone number must have 10 digits.” << endl; bool isValidPhoneNumber(string pn) { int numberOfDigits = 0; for (int k = 0; k != pn.size(); k++) { if (isdigit(pn.at(k))) numberOfDigits++; } if (numberOfDigits == 10) return true; else return false; } bool isValidPhoneNumber(string pn) { int numberOfDigits = 0; for (int k = 0; k != pn.size(); k++) { if (isdigit(pn.at(k))) numberOfDigits++; } return numberOfDigits == 10; } bool isValidPhoneNumber(string pn); ... cout << “Enter a phone number: ”; string t; getline(cin, t); // prototype int numberOfDigits = 0; for (int k = 0; k != t.size(); k++) { if (isdigit(t.at(k))) numberOfDigits++; } if (numberOfDigits != 10) cout << “A phone number must have 10 digits.” << endl; bool isValidPhoneNumber(string pn); ... cout << “Enter a phone number: ”; string t; getline(cin, t); // prototype if (!isValidPhoneNumber(t))) cout << “A phone number must have 10 digits.” << endl; function
call
 make
use
of
the
 function
that
is
 already
defined
 if (!isValidPhoneNumber(string t)) cout << “A phone number must have 10 digits.” << endl; if (!bool isValidPhoneNumber(t)) cout << “A phone number must have 10 digits.” << endl; bool isValidPhoneNumber(string pn); { int numberOfDigits = 0; for (int k = 0; k != pn.size(); k++) { if (isdigit(pn.at(k)) numberOfDigits++; } return numberOfDigits == 10; } int sum(int begin, int end) { int temp = 0; for (int i = begin; i <= end; i++) { temp += i; } result1
 result2
 return temp; } int main() { int result1, result2; result1 = sum(1, 100); result2 = sum(105, 287); } 1.  Your
program
begins
in
main().
 2.




Two
variables
get
created.
 3.




Assignment!
You
need
to
 evaluate
the
right
hand
side
 expression.
 4.




Jump
to
the
function
 definition.
 5.




Create
the
sum(1,
100)
world.
 sum(1,
100)
world
 1.  Your
program
begins
in
main().
 • In
a
more
technical
term,
it’s
called
a
call
stack.
 2.




Two
variables
get
created.
 •  All
variables
that
get
created
within
sum()
appear
in
 3.




Assignment!
You
need
to
 this
space.
 evaluate
the
right
hand
side
 int sum(int begin, int end) { int temp = 0; for (int i = begin; i <= end; i++) { temp += i; } result1
 result2
 return temp; } int main() { int result1, result2; result1 = sum(1, 100); result2 = sum(105, 287); } expression.
 4.




Jump
to
the
function
 definition.
 5.




Create
the
sum(1,
100)
world.
 sum(1,
100)
world
 int sum(int begin, int end) { int temp = 0; for (int i = begin; i <= end; i++) { temp += i; } result1
 result1
 result2
 return temp; } 5050
 int main() { int result1, result2; 5050
 result1 = sum(1, 100); result2 = sum(105, 287); } 6.




Create
argument
variables.
 7.




Copy
the
passed
values
in.
 8.




Run
the
code.
 9.




...
 10.



When
encountered
a
return
 statement,
it
“returns”
a
value
 and
destroys
the
sum(1,
100)
 world.
 11.


We
finished
evaluating
the
rhs
 sum(1,
100)
world
 expression.
Now
store
it
in
 begin
 end
 temp
 result1.
 1
12.


Move
on.
 100
 5050
 int sum(int begin, int end) { int temp = 0; for (int i = begin; i <= end; i++) { temp += i; } result1
 result1
 result2
 return temp; } int main() { int result1, result2; result1 = sum(1, 100); result2 = sum(105, 287); } 6.




Create
argument
variables.
 7.




Copy
the
passed
values
in.
 8.




Run
the
code.
 9.




...
 10.




When
encountered
a
return
 statement,
it
“returns”
a
value
 and
destroys
the
sum(1,
100)
 world.
 sum(1,
100)
world
 end
 begin
 1
 100
   Instead
of
having
arguments
copied,
make
a
 reference
to
an
existing
variable.
   This
can
be
done
by
adding
an
ampersand
 before
the
argument’s
name.
   Example:
 
void sum(int begin, int end, int& result); void sum(int begin, int end, int& result) { 1.  Your
program
begins
in
main().
 result = 0; 2.




Two
variables
get
created.
 for (int i = begin; i <= end; i++) 3.




Function
call!
 { result += i; 4.




Jump
to
the
function
 } definition.
 result1
 result2
 } int main() { int result1, result2; sum(1, 100, result1); sum(105, 287, result2); } 5.




sum(1,
100,
result)
world
 sum(1,
100,
result)
world
 void sum(int begin, int end, int& result) 6.




Create
argument
variables.
 { 7.




Copy
the
passed
values
in,
and
 result = 0; make
appropriate
references.
 for (int i = begin; i <= end; i++) 8.




Run
the
code.
 { result += i; 9.




...
 } 10.




When
encountered
a
return
 result1
 result1
 result2
 } 5050
 0
 statement,
it
“returns”
a
value
(if
 any)
and
destroys
the
sum
world.
 sum(1,
100,
result)
world
 end
 result
 end
 11.


Move
on.
 begin
 int main() { int result1, result2; sum(1, 100, result1); sum(105, 287, result2); } 1
 100
 &
   A
reference
is
just
another
name
for
an
 already
existing
variable;
no
copy
is
made.
   This
means
the
argument
you
are
passing
in
 must
be
a
variable.
   sum(5, 100, 20);   sum(5, 100, res); // error! // OK   Write
a
function
that
swaps
two
integers,
such
that:
 int x = 4; int y = 7; swap(x, y); cout << x << endl; cout << y << endl; // prints 7 // prints 4   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y)   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y) { x = y; y = x; }   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y) { int temp = x; x = y; y = temp; }   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y) { int temp = x; x = y; y = temp; } ... int y = 4; int x = 7; swap(y, x); cout << y << endl; cout << x << endl; // prints 7 // prints 4 result1
 result1
 x
 y
 temp
 &
 0
 &
 y
 x
 4
 7
   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y) { int temp = x; x = y; y = temp; } ... int y = 4; int z = 7; swap(y, x); cout << y << endl; cout << x << endl; // prints 7 // prints 4 result1
 result1
 x
 y
 temp
 &
 0
 &
 4
 y
 x
 4
 7
   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y) { int temp = x; x = y; y = temp; } ... int y = 4; int z = 7; swap(y, x); cout << y << endl; cout << x << endl; // prints 7 // prints 4 result1
 result1
 x
 y
 temp
 &
 0
 &
 4
 y
 x
 7
 7
   Write
a
function
that
swaps
two
integers.
 void swap(int& x, int& y) { int temp = x; x = y; y = temp; } ... int y = 4; int z = 7; swap(y, x); cout << y << endl; cout << x << endl; // prints 7 // prints 4 result1
 result1
 x
 y
 temp
 &
 0
 &
 4
 y
 x
 7
 4
   10‐min
break
   Simple
calculator
   Given
a
formula
string,
find
the
result.
   A
formula
string
consists
of
   The
formula
takes
the
form
of:
 ▪  two
non‐negative
integers,
and
 ▪  an
operator
(+,
‐,
*,
/)
 ▪  x<op>y
 ▪  examples:
1+3,
239*5,
72/10,
3‐20
 ▪  For
simplicity,
allow
empty
x
and
y(e.g.
+3,
12*)
in
which
case
 we
assume
the
number
is
0.
   Assume
our
calculator
cannot
deal
with
negative
 numbers.
   Write
a
function
that
takes
in
a
string
formula,
and
 writes
the
result
to
result.
 
int calc(string formula, int& result)   It
returns
an
error
code:
   0
if
no
error,
   1
if
the
formula
is
malformed,
 ▪  a
formula
is
well‐formed
if
it
takes
the
form
x<op>y,
with
x
and
y
 being
nonnegative
integers,
and
<op>
being
one
of
the
four
 possible
operators.
   2
if
dividing
by
0
(leaves
result
unchanged),
and
   3
if
the
result
is
negative
(but
still
writes
result
to
result)
 int calc(string formula, int& result) { }
 1.
Write
the
function
header.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? // Strategy: Go through all characters in formula // and look for an operator. // All other chars must be digits. }
 2.
Check
for
errors.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character // If ch is a digit, then move on. // If ch is not a digit, then // check if it is one of the valid operators. } }
 2.
Check
for
errors.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (ch != ‘+’ && ch != ‘-’ && ch != ‘*’ && ch != ‘/’) return 1; } } }
 2.
When
there
is
no
need
to
 look
further,
just
return.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (!isValidOp(ch)) return 1; } } bool isValidOp(char ch) { if (ch != ‘+’ && ch != ‘-’ && }
 ch != ‘*’ && ch != ‘/’) return false; return true; } 3.
I
can
simplify
this.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (!isValidOp(ch)) return 1; } } }
 4.
Does
this
look
right?
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (!isValidOp(ch)) return 1; } } }
 4.
Does
this
look
right?
 It
fails
to
detect
multiple
ops!
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? bool opFound = false; for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (opFound) return 1; // already found one! if (!isValidOp(ch)) return 1; else opFound = true; } } }
 5.
Use
a
bool
trick.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? bool opFound = false; for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (opFound) return 1; // already found one! if (!isValidOp(ch)) return 1; else opFound = true; } } }
 6.
Is
this
correct?

 int calc(string formula, int& result) { // Phase 1: Is formula malformed? bool opFound = false; for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (opFound) return 1; // already found one! if (!isValidOp(ch)) return 1; else opFound = true; } } }
 6.
Is
this
correct?
 What
if
there
is
no
op?

 int calc(string formula, int& result) { // Phase 1: Is formula malformed? bool opFound = false; for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (opFound) return 1; // already found one! if (!isValidOp(ch)) return 1; else opFound = true; } } if (!opFound) return 1; }
 7.
Again,
use
the
bool
trick.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? bool opFound = false; for (int i = 0; i < formula.size(); i++) { char ch = formula.at(i); // i-th character if (!isdigit(ch)) { if (opFound) return 1; // already found one! if (!isValidOp(ch)) return 1; else opFound = true; } } if (!opFound) return 1; }
 8.
Too
long.
Write
a
function
 for
it.
 bool isFormulaWellFormed(string formula) int calc(string formula, int& result) { { bool opFound = Is formula malformed? // Phase 1: false; forool opFound = false; b (int i = 0; i < formula.size(); i++) { for (int i = 0; i < formula.size(); i++) // i-th character { char ch = formula.at(i); ifc(!isdigit(ch)) har ch = formula.at(i); // i-th character { if (!isdigit(ch)) {if (opFound) return false; // already found one! if i(!isValidOp) ch)) f (opFound ( return 1; // already found one! ireturn false;(ch)) f (isValidOp else return 1; eopFound = true; lse opFound = true; } } } if} (!opFound) return false; if (!opFound) return 1; return true; 8.
Too
long.
Write
a
function
 }
 }
 for
it.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? if (!isFormulaWellFormed(formula)) return 1; }
 8.
Too
long.
Write
a
function
 for
it.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? if (!isFormulaWellFormed(formula)) return 1; // Phase 2: Extract the necessary information. // Locate the operator. // Extract two numbers. } 9.
Move
onto
the
next
part.
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? if (!isFormulaWellFormed(formula)) return 1; 10.
Find
the
operator.
 // Phase 2: Extract the necessary information. // Locate the operator. int opL; // for operator’s location in formula char op; for (int i = 0; i < formula.size(); ++i) { if (!isdigit(formula.at(i))) { opL = i; op = formula.at(i); } } // Extract two numbers. }
 int calc(string formula, int& result) { // Phase 1: Is formula malformed? if (!isFormulaWellFormed(formula)) return 1; 11.
Extract
two
strings
for
 integers.
 }
 // Phase 2: Extract the necessary information. // Locate the operator. int opL; char op; for (int i = 0; i < formula.size(); ++i) { if (!isdigit(formula.at(i))) { opL = i; op = formula.at(i); } } // Extract two numbers. // Strategy: ? ... Phase 1 omitted ... }
 // Phase 2: Extract the necessary information. // Locate the operator. int opL = -1; char op; for (int i = 0; i < formula.size(); ++i) { if (!isdigit(formula.at(i))) No,
this
function
is
not
 { defined
for
you
already.
 opL = i; You
need
to
define
it,
 op = formula.at(i); } 
and
you
should
be
able
to
 } define
it
yourself.
 // Extract two substrings... string leftNumS = formula.substr(0, opL); string rightNumS = formula.substr(opL + 1, formula.size() – opL – 1); // and convert them. int leftNum = convertStrToNum(leftNumS); int rightNum = convertStrToNum(rightNumS); opL=
2
 11.
Extract
two
strings
for
 integers.
 1
 2
 +
 3
 4
 5
 12.
Now
compute
the
values,
if
 ... Phase 1 omitted ... you
can.
 ... half of Phase 2 omitted ... // and convert them. int leftNum = convertStrToNum(leftNumS); int rightNum = convertStrToNum(rightNumS); // Phase 3: Do the computation. // Strategy: ? }
 13.
The
rest
should
be
straight
 ... Phase 1 omitted ... forward.
 ... half of Phase 2 omitted ... // and convert them. int leftNum = convertStrToNum(leftNumS); int rightNum = convertStrToNum(rightNumS); // Phase 3: Do the computation. switch(op) { case ‘+’: result = leftNum + rightNum; break; case ‘-’: result = leftNum – rightNum; if (result < 0) return 3; break; ... other cases omitted ... } return 0; }
 13.
The
rest
should
be
straight
 ... Phase 1 omitted ... forward.
 ... half of Phase 2 omitted ... // and convert them. int leftNum = convertStrToNum(leftNumS); int rightNum = convertStrToNum(rightNumS); // Phase 3: Do the computation. switch(op) { case ‘+’: result = leftNum + rightNum; break; case ‘-’: result = leftNum – rightNum; if (result < 0) return 3; break; ... other cases omitted ... } return 0; }
   VC++
demo
   Tip
1:
Validity
Check
Strategy
   Given
parameters,
check
for
all
possible
errors
 first,
returning
the
right
error
code.
If
no
errors,
 then
proceed
with
the
normal
process.
   Tip
2:
Helper
Functions
Help
Simplify
   Consider
writing
functions
that:
 ▪  convert
a
string
into
an
integer
 ▪  check
if
a
character
is
one
of
the
valid
characters
   If
you
haven’t
started,
start
working
on
it
 now!
   Assuming
you
all
read
the
spec,
let
me
say
a
 few
things…
   Well‐formed
   Every
beat
ends
with
a
slash.
   A
note
is
1)
empty,
2)
a
letter,
3)
a
single
digit
followed
   Translatable
 by
a
letter,
or
4)
two
digits
followed
by
a
letter.

   The
case
of
a
letter
does
not
matter.
   The
song
is
well‐formed.
   For
all
beats
for
which
a
sustained
note
is
in
effect,
 except
the
first,
the
beat
consists
only
of
a
slash.
   The
song
string
can't
end
prematurely.
   The
length
of
a
sustained
note
cannot
be
0
or
1.
   Examples
   //////o/y/3g///
–
well‐formed
and
translatable
 ▪  translates
to
xxxxxxoyGGG
   /2k/
–
neither
well‐formed
nor
translatable
   100g/
‐
neither
well‐formed
nor
translatable
   gy/
–
neither
well‐formed
nor
translatable
   y/2g/5R//
–
well‐formed,
but
not
translatable
   2y//g/b/
–
well‐formed
and
translatable
 ▪  translates
to
YYgb
   isWellFormed(song)
should
return
true
if
song
 is
well‐formed,
even
if
it
is
not
translatable.
 Case
 song
translatable
 song
not
well‐formed
 song
well‐formed,
 ‘/’
not
present
with
a
 sustained
note
in
effect
 song
well‐formed,
but
 ends
prematurely
 instructions
 unchanged
 unchanged
 badBeat
 unchanged
 index
of
the
erroneous
beat
 return
 0
 1
 2
 translated
version
 unchanged
 unchanged
 1
+
(#
beats
in
the
song)
 index
of
the
erroneous
beat
 3
 4
 song
well‐formed,
but
a
 unchanged
 beat
specifies
a
sustained
 note
of
length
<
2
 If
more
than
one
errors,
detect
the
leftmost
one.
 int translate(string song, string& instructions, int& badBeat) ...
View Full Document

This note was uploaded on 02/02/2011 for the course CS 31 taught by Professor Melkanoff during the Spring '00 term at UCLA.

Ask a homework question - tutors are online