ucla cs 31 lecture5 post on functions
DESCRIPTION
Functions programming class. How to create functions in C++.TRANSCRIPT
Wednesday, October 20th
• Review Challenge• A new data type: bool• “Short Circuiting”• Introduction to Function
Calls
Review ChallengeWrite 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: boolThe 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;
cin >> age; if (age > 33) oldPerson = true; else oldPerson = false; …}
int main(void){ bool bigger;
bigger = 10 > 3;
if (bigger == true) cout << “10 is > than 3\n”;}
oldPerson
?? age
-44
17
17false bigger ??true
More bool Examplesint main(void){ bool bigEars; ...
if (bigEars == true) cout << “U got big Ears!”;
if (bigEars) cout << “U got big Ears!”;}
There are two different ways to check if a boolean variable is true.
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!”;}
More bool Examples
#include <iostream>#include <cstdlib>
int main(void){ bool done = false; int myNum = rand( ); // 0 to 65535
while ( done == false) { int guess; cout << “Guess my #: “; cin >> guess; if (guess == myNum) done = true; } cout << “You got it!\n”;}
Boolean variables are often used to decide when to end a loop.
done
false
myNum
721
The rand function returns a random integer between
0 and 65535. rand is a function just like main is.
guess -10
Guess my #:721
721721 == 721??
true
true == false??
You got it!
Short Circuiting
if (cute == true || smart == true || rich == true)
cout << “Hey, want to go on a date?”; Consider the above expression…
If you’re either cute, or smart, or rich, then I’d like to go out with you.
Let’s say that I happen to know you’re cute.
bool cute = true;
Once I know you’re cute, I no longer need to waste time asking the other two questions…
Short Circuiting
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.
bool cute = true;
This speeds
your program up!
Short Circuiting With OR ||
int eyes; cin >> eyes;
if (eyes < 2 || eyes > 8 || eyes == 5) cout << “FREAK!\n”;…
16
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 doesn’t
need to evaluate anything else.
16 < 2 16 > 8
Short Circuitingint age; cin >> age;
if (age > 18 && smart == true && cute == true) cout << “<witty pickup line here>.\n”;else cout << “Uh… See you later!\n”;
17
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 doesn’t
need to evaluate anything else.
17 > 18??
Short Circuiting
What does this program print if the user types in
11 and 10?
int main(void){ int hw, sleep;
cout << "Enter hours of HW: "; cin >> hw; cout << "Enter hours of sleep: "; cin >> sleep;
if ( hw++ > 10 || ++sleep < 8 ) cout << “You nerd!\n";
cout <<"hw is " << hw << "\n"; cout <<"sleep is " << sleep << "\n";}
hw 50 sleep 69
Enter hours of HW:11Enter hours of sleep:10
1110
11 > 10???
12
hw is 12sleep is 10
You nerd!
Next Topic: Functionsint main(void){ int i, n, f;
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;}
What’s wrong with this program?
FunctionsIn 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!
FunctionsA 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 Functionsint 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;}
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);}
FunctionsIn 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(); // call to a functionComputeAverage();PrintScores();
}
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, teaseAs always, our program starts in main!
Carey is
totally cool
David S.
would like to be totally cool
The end.
When we reach a function, we run the logic in the function and then continue with the next line of the program.
Passing Data To Functions
void cube( int n ){ int c = n*n*n;
cout << n << “ cubed is “ << c << “\n”;}
int main(void){ int value;
cout >> “Enter a value: ”; cin >> value;
cube(value);
cube(value+1);}
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.
value
93Enter a value: 2
2
2
2 n
2 c
2*2*2 8
2 cubed is 8
3
3 n
3 c
3*3*3 27
3 cubed is 27
Returning Data From Functions
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;}
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
area71
Enter radius: 10
10
10
10 rad 10 a -1
3.14 * 10 * 10
314
314
314
314
Area: 314.00
The Function Definitionfloat 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 function’s actual logic.
1. A function header line that specifies:
a. The func’s name
Each func. def. has:
b. The func’s parametersb. The type of value the function returns.
I return floating-point numbers.
float ComputeArea( float rad )
2. The function body.
{ float a; a = 3.14 * rad * rad;
return( a );}
3. A return statement that sends a value back to the caller.
return( a );
float ComputeArea( float rad ){ float a; a = 3.14 * rad * rad;
return( a );}
int main(void){ float area;
area = ComputeArea( 4.0 ); cout << “Area is: “ << area;}
Function ParametersA function may have one
or more formal parameters.
They are treated just like any other local variable.
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.
4.0
You must make sure that your actual parameter and
formal parameter types match.
char x = ‘A’;x
// ERROR!
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){ int num_zits = 4, total;
total = TotalFluid( num_zits , .52 ); cout << “Ounces of fluid: “ << total;}
Functions may have multiple parameters.
Make sure that the type of each actual
parameter matches the type
of each formal parameter!
Each formal parameter should be separated by a comma and must have its own type
and name specified .
Function Parameters
Functions may also have no parameters.
Then, make sure you don’t pass any parameters to the function when you
call it.
In this case, you should place the word “void” in between the
parentheses in the function definition.
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”;}
float ComputeArea( float rad ){ float a; a = 3.14 * rad * rad;
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); ...
In this case, our top function has a return type of “float” so it should return float-type values.
float
For instance, it shouldn’t try to return char values.
char your_grade; your_grade = ‘A’; return(your_grade);
char your_grade; your_grade = ‘A’; return(your_grade); // ERROR!
This may result in either a compiler error or a run-time error!
Returning from a FunctionA function can return any single type of value it likes: int, char, float, double, long, etc.
int ComputeNoseHairs(int age){ if (age < 33) return(age * 10);
}
int main(void){ int nh;
nh = ComputeNoseHairs(18); cout << “Will has “ << nh << “ nose hairs!\n”;}
When the program reaches a return
statement…
The current function ends immediately and sends its result value
back to the caller.
cout << “Old and hairy!\n”;return(age*100);
Returning from a Function
nh 9991
18age 18
18 < 33?
180
180
Will has 180 nose hairs!
18*10180
Returning from a Functionvoid 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”;}
In this case, you may still use the return statement to immediately exit the function, but you can’t
specify a value.
If a function doesn’t need to return a value, it
should have a void return type.
This means: “I don’t return any
value.”
85 grade 85
float ComputeArea( float rad ){ float a; a = 3.14 * rad * rad;
return( a );}
int main(void){ float area;
area = ComputeArea( 4 );
cout << “Area is: “ << area;}
Variable Rules
A function can only access its own variables, but not other function’s
variables.
Why is this important?
So ComputeArea can access a and rad but can’t access the area variable.
cout << area; // ERROR!
cout << rad; // ERROR!Similarly, main can access area but cannot access the rad or a variables.
A function may have its own private “local”
variables.
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; cin >> n; UCLARules(n);}
void UCLARules(int x){ int j;
for (j=0;j<x;j++) cout << “UCLA Rules\n”;}
What’s the difference between these two programs?
Function Prototypes
int main(){ int n; cin >> n; UCLARules(n);}
void UCLARules(int x){ int j;
for (j=0;j<x;j++) cout << “UCLA Rules\n”;}
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.
It’s confusing!
Function Prototypes
int main(){ int n; cin >> n; UCLARules(n);}
void UCLARules(int x){ int j;
for (j=0;j<x;j++) cout << “UCLA Rules\n”;}
This is also confusing for the C++ compiler.
When compiling the main function, it sees
the function call to UCLARules but it
doesn’t know about this function yet.
This results in an error.
Function Prototypes
int main(){ int n; cin >> n; UCLARules(n);}
void UCLARules(int x){ int j;
for (j=0;j<x;j++) cout << “UCLA Rules\n”;}
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.
void UCLARules(int x)Simply copy the function’s header line above the first reference to the function.
Then add a semicolon at the end.
;
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(x,y); cout << “The square’s area is “ << area;}
Note: function names are
case sensitive in C++.
gETaREA // ERROR!