You are on page 1of 31

Wednesday, October 20th

Review Challenge
A new data type: bool
Short Circuiting
Introduction to Function Calls

Review Challenge
Write a program that reverses a string

void main(void)
{
string s = a man a plan a canal panama;
// write your code here to reverse the string

cout << s;
}

// prints amanap lanac a nalp a nam a;

Boolean Variables: bool


The bool data type is another C++ type just like
int, float, or short.
bool variables can hold only two values: true or false
int main(void)
{
bool oldPerson;
int age;

int main(void)
{
bool bigger;

17

cin >> age;


if (age > 33)
oldPerson = true;
else
oldPerson = false;

age
oldPerson

bigger = 10 > 3;

17
-44
false
??

if (bigger == true)
cout << 10 is > than 3\n;

bigger

true
??

More bool Examples


int main(void)
{
bool bigEars;
...
if (bigEars == true)
cout << U got big Ears!;

There are two different


ways to check if a boolean
variable is true.

if (bigEars)
cout << U got big Ears!;

There are two different


ways to check if a boolean
variable is false.

int main(void)
{
bool bigEars;
...
if (bigEars == false)
cout << Small ears!;

if ( ! bigEars )
cout << Small ears!;

randExamples
function returns a
MoreThe
bool
#include <iostream>
#include <cstdlib>

random integer between


0 and 65535. rand is a
function just like main is.

int main(void)
{
bool done = false;
int myNum = rand( ); // 0 to 65535

true == false??

while ( done == false)


{
int guess;
cout << Guess my #: ;
cin >> guess;
721
if (guess == myNum)
done = true;
}
cout << You got it!\n;

Boolean variables are


often used to decide
when to end a loop.
Guess my #: 721
You got it!

== 721??

guess
myNum
done

721
-10
721
true
false

Short Circuiting
bool cute = true;
if (cute == true || smart == true || rich == true)
cout << Hey, want to go on a date?;
Consider the above expression
If youre either cute, or smart, or rich, then Id
like to go out with you.
Lets say that I happen to know youre cute.
Once I know youre cute, I no longer need to
waste time asking the other two questions

Short Circuiting
bool cute = true;

s
d
e
!
e
p
p
s
u
s
i
h
T rogram
p
r
u
yo

if (cute == true || smart == true || rich == true)


cout << Hey, want to go on a date?;
This is called short-circuiting.
In such an if statement, C++ will evaluate the
expressions from left-to-right
The moment C++ finds a condition that satisfies
the if statement, it will skip the rest of the
cases and continue with the next statement.

Short Circuiting With OR ||


int eyes;
cin >> eyes;

16

16 < 2
16 > 8
if (eyes < 2 || eyes > 8 || eyes == 5)
cout << FREAK!\n;

Case 1: Your if statement uses all || as above.


As soon as an expression (e.g. eyes > 8) is found to
be true, C++ knows that it doesnt need to evaluate
anything else.

Short Circuiting
17
int age;
cin >> age;
17 > 18??
if (age > 18 && smart == true && cute == true)
cout << <witty pickup line here>.\n;
else
cout << Uh See you later!\n;
Case 2: Your if statement uses all && as above
As soon as an expression (e.g. age > 17) is found to
be false, C++ knows that it doesnt need to
evaluate anything else.

Short Circuiting
int main(void)
{
int hw, sleep;
cout << "Enter hours of HW: ";
cin >> hw;
cout << "Enter hours of sleep: ";
cin >> sleep;

11 > 10???
if ( hw++ > 10 || ++sleep < 8 )
cout << You nerd!\n";
cout <<"hw is " << hw << "\n";
cout <<"sleep is " << sleep << "\n";
}

hw 50
12
11
sleep 69
10

What does this


program print if
the user types in
11 and 10?
Enter hours of HW: 11
Enter hours of
sleep: 10
You nerd!
hw is 12
sleep is 10

Next Topic: Functions


int main(void)
{
int i, n, f;

Whats wrong with this program?

n = 5;
for (i=1,f=1;i<=n;i++)
f *= i;
cout << n << factorial: << f;
...
n = 15;
for (i=1,f=1;i<=n;i++)
f *= i;
cout << n << factorial: << f;
...
n = 6;
for (i=1,f=1;i<=n;i++)
f *= i;
cout << n << factorial: << f;
}

Functions
In the previous example, we repeated the same
logic over and over and over
Not only does this make our program hard to
read, but it also may introduce bugs!
for (i=1,f=1; i<=n ;i++)
f *= i;
// calculate n factorial
cout << n << factorial: << f;
...
for (i=1,f=1; i<n ;i++)
f *= i;
// calculate n factorial
cout << n << factorial: << f;
}

We can solve these problems with C++ functions!

Functions
A function is a special component of a program that
performs a certain task (like computing a factorial).

Each function is self-contained and independent of


the other logic in your program.

Each function should perform a single, well-defined


task.
Using functions, we can simplify a program and split it
up into smaller, more manageable components.

Simplifying With Functions


int main(void)
{
int i, n, f;
n = 5;
for (i=1,f=1;i<=n;i++)
f *= i;
cout << n << factorial is
<< f;
...
n = 15;
for (i=1,f=1;i<=n;i++)
f *= i;
cout << n << factorial is
<< f;
...
n = 6;
for (i=1,f=1;i<=n;i++)
f *= i;
cout << n << factorial is
<< f;
}

void fact(int n)
{
int i,f;

}
int main(void)
{
fact(5);
...
fact(15);
...
fact(6);
}

Functions

In a well-written program, the main function calls


other functions to do the work of the program.
main should not do all of the work itself:
int main(void)
{
GetTestScores();
ComputeAverage();
PrintScores();
}

// call to a function

A Simple Program With Functions


void praise()
{
cout << totally cool\n;
}
void tease()
{
cout << would like to be ;
praise();
}
int main(void)
{
cout << Carey is ;
praise();
cout << David S.;
tease();
cout << The end.\n;
}

This program has three


functions: main, praise, tease

As always, our program


starts in main!
When we reach a function,
we run the logic in the
function and then continue
with the next line of the
program.
Carey is totally cool
David S. would like to
be totally cool
The end.

Passing Data To Functions


2
3
int n )

void cube(
{
3*3*3
2*2*2
int c = n*n*n;

n
c

2
3

8
27

cout << n << cubed is <<


c << \n;
}
int main(void)
{
int value;
cout >> Enter a value: ;
cin >> value;

cube(value);

3
cube(value+1);
}

value 93
2

Sometimes you need to pass


values to a function for it to
work on.
To do so, when we call the
function, we place the value(s)
we want to send in between
the parentheses.
When we define the function,
we specify the type and name
of each parameter in
between the parentheses.
Enter a value: 2
2 cubed is 8
3 cubed is 27

Returning Data From Functions


10

float ComputeArea( float rad )


{
float a;
3.14 * 10 * 10
a = 3.14 * rad * rad;

314

return( a );
}
int main(void)
{
float r, area;
cout >> Enter radius: ;
cin >> r;

10
314
area = ComputeArea( r );

cout << Area: << area;


}

rad 10
a 314
-1

Sometimes you need to send a


value back from a function to
the caller of the function.
To do so, when we use the
return statement in our
function.

r 913
10
area 314
71
Enter radius: 10
Area: 314.00

The Function Definition

I return floatingpoint numbers.

float ComputeArea( float rad )


{
float a;
a = 3.14 * rad * rad;
return( a );
}
int main(void)
{
float r, area;
cout >> Enter radius: ;
cin >> r;
area = ComputeArea( r );
cout << Area: << area;
}

The function definition is


where you put the functions
actual logic.
Each func. def. has:
1. A function header line
that specifies:
a. The funcs name
b. The funcs parameters
b. The type of value the
function returns.
2. The function body.
3. A return statement
that sends a value back
to the caller.

Function Parameters
4.0

float ComputeArea( float rad )


{
float a;
a = 3.14 * rad * rad;

A function may have one or


more formal parameters.
They are treated just like
any other local variable.

return( a );
}
int main(void)
{
float area;
// ERROR!
char x = A;
area = ComputeArea( 4.0
x );
cout << Area is: << area;
}

You must make sure that your


actual parameter and formal
parameter types match.

A value/variable passed to
the function is called an
actual parameter.
The actual parameter value
is copied into the formal
parameter variable when you
call the function.

Function Parameters
#include <iostream>
#include <cmath>
using namespace std;
float TotalFluid(int zits, float ozPerZit)
{
float totalOunces;
totalOunces = zits * ozPerZit;
return(totalOunces);
}
int main(void)

Functions may have


multiple parameters.
Each formal
parameter should be
separated by a comma
and must have its own
type and name
specified .

{
int num_zits = 4, total;
total = TotalFluid( num_zits , .52 );
cout << Ounces of fluid: << total;
}

Make sure that the


type of each actual
parameter matches
the type of each
formal parameter!

Function Parameters
void praise(void)
{
cout << totally cool\n;
}
void tease() // ( ) is the same as void
{
cout << would like to be ;
praise();
}
int main(void)
{
cout << Carey is ;
praise();
cout << David S.;
tease();
cout << The end.\n;
}

Functions may
also have no
parameters.
In this case, you
should place the word
void in between the
parentheses in the
function definition.
Then, make sure you
dont pass any
parameters to the
function when you
call it.

Returning from a Function


float ComputeArea( float rad )
{
char your_grade;
float
a;
a = 3.14 * rad * rad;
your_grade = A;
return(your_grade);
// ERROR!
return(
a );
}
long ComputeBoogies(int age)
{
long boogers = 10 * age*age;
return(boogers);
}
int main(void)
{
float area;
long snot;
area = ComputeArea( 10 );
snot = ComputeBoogies(32);
...

A function can return any


single type of value it likes:
int, char, float, double, long,
etc.
In this case, our top function
has a return type of float
so it should return floattype values.
For instance, it shouldnt try
to return char values.
This may result in either a
compiler error or a run-time
error!

Returning from a Function


age

18

18

int ComputeNoseHairs(int age)


{
18 < 33?
if (age < 33)
return(age * 10);

180
18*10
Old and

cout <<
hairy!\n;
return(age*100);
}
int main(void)
{
int nh;

The current function


ends immediately and
sends its result value
back to the caller.
Will has 180 nose
hairs!

180
nh =

ComputeNoseHairs(18);
cout << Will has << nh <<
nose hairs!\n;

When the program


reaches a return
statement

nh 9991
180

Returning from a Function


85

void PrintGrade(int grade)


{
if (grade >= 90)
{
cout << A;
return;
}
if (grade >= 80)
{
cout << B;
return;
}
cout << Study harder!;
}
int main(void)
{
PrintGrade(85);
cout << Done!\n;
}

grade

85

If a function doesnt need


to return a value, it should
have a void return type.
This means:
I dont return any value.
In this case, you may still
use the return statement
to immediately exit the
function, but you cant
specify a value.

Variable Rules
float ComputeArea( float rad )
{
float a;
a = 3.14 * rad * rad;

A function may have its own


private local variables.

A function can only access


its own variables, but not
other functions variables.

int main(void)
{
float area;

So ComputeArea can access


a and rad but cant access
the area variable.

cout << area;

// ERROR!

return( a );

area = ComputeArea( 4 );

cout << rad;

// ERROR!

cout << Area is: << area;


}

Similarly, main can access


area but cannot access the
rad or a variables.

Why is this important?

Function Prototypes
void UCLARules(int x)
{
int j;
for (j=0;j<x;j++)
cout << UCLA Rules\n;

int main()
{
int n;
cin >> n;
UCLARules(n);

int main()
{
int n;

void UCLARules(int x)
{
int j;

cin >> n;
UCLARules(n);
}

for (j=0;j<x;j++)
cout << UCLA Rules\n;
}

Whats the difference between these two


programs?

Function Prototypes
In this example, a function
(main) calls another
function (UCLARules) that
is defined later in the
program.
This is like a novel that
refers to a character,
but the character is
introduced in a later
chapter.
Its confusing!

int main()
{
int n;
cin >> n;
UCLARules(n);
}
void UCLARules(int x)
{
int j;
for (j=0;j<x;j++)
cout << UCLA Rules\n;
}

Function Prototypes
This is also confusing for
the C++ compiler.
When compiling the main
function, it sees the
function call to UCLARules
but it doesnt know about
this function yet.
This results in an error.

int main()
{
int n;
cin >> n;
UCLARules(n);
}
void UCLARules(int x)
{
int j;
for (j=0;j<x;j++)
cout << UCLA Rules\n;
}

Function Prototypes
If you would like to call a
function defined later in the
program, you must add a special
line called a prototype above
your call to the function.

;
int main()
{
int n;
cin >> n;
UCLARules(n);
}

Simply copy the functions


header line above the first
reference to the function.
Then add a semicolon at the
end.

void UCLARules(int x)
{
int j;
for (j=0;j<x;j++)
cout << UCLA Rules\n;
}

Think of this as an introduction to your new function. It tells


your other functions how to use it, even if its defined later.

Functions: Case Sensitivity


#include <iostream>
#include <cmath>
using namespace std;
float GetArea(float width, float height)
{
float ar;
ar = width * height;
return(ar);
}
int main(void)
{
float x = 3, y = 4, area;
area = gETaREA
GetArea(x,y);
// ERROR!
cout << The squares area is << area;
}

Note: function
names are case
sensitive in C++.

You might also like