-
Summary of what we learned last week
Basics of C++
Our first program: Hello world
Format of a program
Syntax of literals, keywords, symbols, variables
Data types
int (short, long, unsigned)
float/double
char
Arithmetic operations
Assignment (compound) operators
Standard input (cin) and output (cout)
More complex arithmetic operations and operator
precedence
-
Functions Functions Functions Functions (Chapter 2 (Chapter 2
(Chapter 2 (Chapter 2 Continued)Continued)Continued)Continued)
Main function will soon get big
Solution: Divide and Conquer
divide your problem into small ones
write one function for each
combine them in the main program
Advantages:
Main is organized into modular pieces
When you need to change something, you only
change that function and not main
Reuse the same code piece several times e.g. all programs use
cin and cout
-
Functions Functions Functions Functions
Without functionWithout functionWithout functionWithout
function
#include using namespace std;
/* traditional first program */
int main(){
cout
-
A program is a collection of functions and classes main and
other programmer defined functions
only main is executed automatically when the program starts
other functions must be called to be executed
Programmer-defined functions piece of code to do a specific job
must be declared before using (calling)
return-type function-name(parameters){
local variablesstatements
}
to execute a function just write its name (and arguments for
parameters) When a function is called, execution order temporarily
jumps to function
after the function ends, execution order goes back to the
caller
Syntax of Functions Syntax of Functions Syntax of Functions
Syntax of Functions
-
Syntax for Functions Syntax for Functions Syntax for Functions
Syntax for Functions
#include using namespace std;
void Hello(){cout
-
Drawing Head Without functions
Draws a head but not so modular
To change head style, main needs to change.
Is this so bad?
What if you want to draw several heads like a totem?
You have to duplicate code
#include using namespace std;int main(){
cout
-
Drawing Head With functions
This one is more complicated, but what are the advantages?
Modularity
Change head style just change functions
What about eyeglasses?
Code re-use (not duplicated)
Multiple heads lets see totem.cpp
parts.cpp
#include using namespace std;
// functions appear here
int main(){
Hair(); Sides();Eyes(); Ears(); Smile();Sides();return 0;
}
-
Functions with Parameters You may need to pass data into a
function when you call it
Consider a generic function to calculate the area of any circle
and display it how will the function know the radius?
solution: parameters function is defined without knowing the
value of the radius
value of radius is passed to the function when it is called
parameters are defined similar to variablestype name Example:
float radius
return-type func-name(type param1,,type param){
local variables
statements
}
-
Area calculation with parameterized function#include
using namespace std;
// area calculation program that employs functions
void calculate_area(float radius)
{
float area;
area = 3.14 * radius * radius;
cout
-
Area calculation with parameterized function
#include
using namespace std;
// area calculation program that employs functions
void calculate_area (float radius)
{
float area;
area = 3.14 * radius * radius;
cout
-
#include
using namespace std;
// area calculation program that employs functions
void calculate_area (float radius)
{
float area;
area = 3.14 * radius * radius;
cout
-
#include
using namespace std;
// area calculation program that employs functions
void calculate_area (float radius)
{
float area;
area = 3.14*radius*radius;
cout
-
Functions with Parameters Parameters and Arguments
parameter is the generic name used in function radius in the
calculate_area function
argument is the value passed to function while it is called
2.5
r (actually current value of r is passed)
r / 2 (actually current value of r / 2 is passed)
Parameter list provides type and name of the parameter Argument
type must match parameter type
Functions may have multiple parameters corresponding arguments
are separated by commas
in the same order of parameter list
be careful about the type matching
Functions may call other functions (have seen in the totem
example and will see in the next example)
-
Functions with ParametersFunctions with ParametersFunctions with
ParametersFunctions with Parameters Parameters versus Local
Variables
Parameters are defined and used locally, but their initial
value
comes from the caller function via arguments
Local variables are defined and used within the function
Initial value does not come from the caller function
While designing your functions, think carefully about local
variables and parameters
If you need to pass the initial value from the caller function,
then
it should be a parameter.
If you wont pass the initial value, then it should be a
local
variable.
Example: in calculate_area function
area is a local variable since we do not pass its initial value
from main
radius is a parameter since we need to pass its initial value
from main
Unnecessary parameters may cause problems and grade
reduction (for homework)
-
Old McDonalds Farm Goal is to have a modular program (with
functions) to display the song
each verse repeats using a different animal
refrain parts repeat within verses
a partial output (with two animals only) below:
Old MacDonald had a farm, Ee-igh, Ee-igh, oh!
And on his farm he had a cow, Ee-igh, Ee-igh, oh!
With a moo moo here
And a moo moo there
Here a moo, there a moo, everywhere a moo moo
Old MacDonald had a farm, Ee-igh, Ee-igh, oh!
Old MacDonald had a farm, Ee-igh, Ee-igh, oh!
And on his farm he had a pig, Ee-igh, Ee-igh, oh!
With a oink oink here
And a oink oink there
Here a oink, there a oink, everywhere a oink oink
Old MacDonald had a farm, Ee-igh, Ee-igh, oh!
-
Old McDonaldOld McDonaldOld McDonaldOld McDonalds Farm s Farm s
Farm s Farm
(Design of Functions)(Design of Functions)(Design of
Functions)(Design of Functions)
Which functions do we need?
a function for only Ee-igh, Ee-igh, oh!
a function for the refrain (nakarat)
a function for And on his farm ... line
animal is parameter
a function for With a ..., And a ..., Here a ... lines
noise of the animal is a parameter
a function for the whole verse
-
Old McDonalds Farm (Program 1) See oldmac1.cpp
What is the problem? We need a new function for a new animal
(e.g. chicken)
Cow and Pig functions are duplicates of each other.
Solution: Put the common code into a new function for the whole
verse
-
Old McDonalds Farm (Program 2) See oldmac2.cpp
Verse does the common work with 2 parameters first one is for
animal, second is for noise therefore it is called using 2
arguments first one is for animal, second is for noise
order of arguments is important
Functions call functions Refrain calls EiEio
Verse calls Refrain
animal is used as parameter name in two functions Should we need
to use the same parameter name in both cases? Or can we use
different names in two different functions?
Same questions are valid for noise as well.
Answer is Yes we can use different names.
Can we input animal and noise?
-
Mac Donalds farm with user input We want the user to enter/input
values for animal and noise
Enter the name of an animal: sheepEnter noise that a sheep
makes: baahOld MacDonald had a farm, Ee-igh, Ee-igh, oh!And on his
farm he had a sheep, Ee-igh, ee-igh, oh!With a baah baah hereAnd a
baah baah thereHere a baah, there a baah, everywhere a baah baahOld
MacDonald had a farm, Ee-igh, Ee-igh, oh!
Well pass the user-entered values to the Verse function The
input stream cin takes input from the keyboard using operator
>>
Values that are input are stored in variables and then passed to
function verse as arguments
see macinput2.cpp
-
Mac Donalds farm with user input// other functions goes here
(see macinput2.cpp)
void Verse(string animal, string noise){ // this function doesnt
change// see the source code for the function code
}
int main(){
string animal; // variable for name of animalstring noise; //
variable for noise it makes
cout > animal;
cout
-
Analysis of the Run1. input value sheep is stored in variable
animal
2. input value baah is stored in variable noise
3. sheep and baah values are passed to function Verse as
arguments as well as used in cout in main
-
Variables (review from previous
lectures) Variables are used to store values in memory
memory locations that are accessed using a name
Each variable has a type, a name (identifier), and a value
Methods to give values to variables Assignment, using =
Input, using cin
Definition:
type variable_names_separated_by_comma;
-
Where to define variables You can define variables anywhere
within a function
as long as it is defined before its first use
Two common places of variable definition At the beginning of the
function in which theyre used:
{string animal, noise;cout > animal;cout animal;cout
-
Where to define variables NO GLOBAL VARIABLES
A global variable is a variable defined outside the function
bodies
#include using namespace std;
int global_number;
int main(){
cout
-
Variable Initialization Variables have garbage (junk values)
until
they are assigned a value using assignment operator or myint =
5;
an input is stored into them (using cin statement) cin >>
myint;
Variables must be given a value before being used for the first
time in an expression or an output statement or as an argument to a
function idea behind this rule: you can never know what is inside
of an uninitialized variable !
not a syntax error, compiler may or may not warn you!
You may initialize variables at the declarationint mynumber =
5;
After initialization, you may change the value stored in a
variable several times that is why they are named as variable
-
Scope of a Variable and Parameter
Not explained in the book in this way
RULE 1: A variable or parameter can be referred only
within the function in which it is declared
e.g. you cannot refer the variable animal in function Eieio
RULE 2: A specific identifier can be used several times in
different functions as variable or parameter names.
Those are actually different variables/parameters.
e.g. animal and noise are used both in main (as variable)
and
Verse (as parameter)
RULE 3: A specific identifier must be unique within a
function
e.g. you cannot define a local variable animal in Verse
since
there is a parameter named animal
Detailed scope rules will be given later in this course
-
Reading Assignment
Section 3.3 (page 83)
Case Study: Pizza Slices
Similar to circle area calculation program
Run the program pizza.cpp
-
Functions that return values
Functions weve written so far are void functions They do a job
and return back to caller, but without a value
Parameters are used for one-way data transfer into the function
to be called
How about transfer a computed value out of a function? to the
main program or to other function (the caller)
Non-void functions can return values of any type function call
becomes an expression
when the function finishes, the function call is replaced by the
returned value
this way, values computed in functions can be transferred into
the caller functions
void function call is not used in an expression, i.e. no value
is associated with a void function
Head();DoThat();Verse("cow", "moo");
-
Functions that return values
Example (see area_func_return.cpp):
suppose circlearea function takes the radius as parameter and
returns the
area.
In the program we call circlearea as an expression (you have to
use the
returned value somewhere)
area = circlearea(r);
cout
-
Math library functions Mathematical functions like square root,
logarithm, sin, cos, etc.
Prototypes are in header file cmath#include
Full list is in page 758 (Table F.1) partial list is in table
4.5. correction in Table F.1: int abs (int x)
Keep these math library functions on your cheat-sheet for the
exam
Example use of function sqrt see usemath.cpp
how did we use sqrt function? in cout as an expression
could we use sqrt in assignment? How?
yes, lets do it.
what happens if value is negative?
try and see!
we can add some if statements to display an error message in
case of negative value
-
return-type func-name(parameters){local variables
statements
}
Function Syntax
Example: Function to calculate volume of a sphere
double SphereVol(double radius){
return 4.0*radius*radius*radius*acos(-1)/3;}
function body
-
Function Syntax
double SphereVol(double radius){
return 4.0*radius*radius*radius*acos(-1)/3;}
Function heading/prototype shows return type. return type can be
any type (including string)
theoretically return type may be Robot too, but in practice
Robot class is not designed to be used as the return type
you do not see any syntax error, but execution may be
problematic. So do not return a Robot from a function
Function body may have several statements in it
return statement is used to determine the value returned
fromfunction, so the expression after it must be of the return
type
Function body must include at least one return statement
The return statement causes the function to exit immediately and
to return the value after return
A function can have more than one return statements, but only
one is executed when the function is called (see next example)
Only one return is a good programming style to have control of
bigger functions
-
Functions can return strings
string WeekDay(int day)
// precondition: 0
-
Function documentation
Functions usually have a precondition
What conditions (e.g. value of parameters) must be true for
the
function to work as intended?
If there are no parameters, then no precondition
Some functions work for every parameter value
no precondition
Functions always have a postcondition
If precondition is satisfied what does the function do? What
does
the function return?
-
Example Compare cost of pizza sizes
Problem: Calculate and compare price per square inch of
large
and small size pizzas
Solution:
A function, say Cost, that takes the pizza radius and price as
parameters
and returns price per square inch
In main()
input radiuses and prices of large and small pizzas
calculate the per square inch costs by calling the cost
function
display the results on screen
compare the unit costs to find out which one is best value
See pizza2.cpp
-
Example - When is a year a leap year?
Every year divisible by four is a leap year
Except years divisible by 100 are not
Except years divisible by 400 are
Alternatively:
Every year divisible by 400 is a leap year
Otherwise, years divisible by 100 are not leap years
Otherwise, years divisible by 4 are leap years
Otherwise, not a leap year
Boolean functionbool IsLeapYear(int year);
// pre: year > 0
// post: return true if year is a leap year
-
Implementation and use of leap year functionbool IsLeapYear(int
year)// precondition: year > 0// postcondition: returns true if
year is a leap year, else returns false {
if (year % 400 == 0) // divisible by 400{ return true;}else if
(year % 100 == 0) // divisible by 100{ return false;}else if (year
% 4 == 0) // divisible by 4{ return true;}return false;
}int main(){
int year;cout > year;if (IsLeapYear(year)){ cout
-
Theres more than one way
No if/else necessary in the function body
bool IsLeapYear(int year)// precondition: year > 0// post:
return true if year is a leap year{
return ( year % 400 == 0 ) ||( year % 4 == 0 && year %
100 != 0);
}
How does this work?
Is this version more efficient?
Are these two versions different from user perspective?
-
Function Prototype (from 2.6) Functions definition has two
parts
function heading
name, parameters, return type
function body (local variables and statements within curly
brackets)
void display (string name)
{
cout
-
Function Prototype Example Problem
What is the problem below (program order.cpp) ?
void Hi (string name){
cout
-
Function Prototype Solution
Add function prototypes to the beginning (order2.cpp)
#include #include using namespace std;
void Hi(string);void Greetings();
void Hi (string name){
cout
-
Function Prototypes *** Do not forget semicolon after the
prototype
definition ***
no semicolon after the parameters in normal definition
Sometimes prototypes are not necessary
if the order of function calls allows
but it is good programming practice to have them
Parameter names are not needed in prototypes
but it is OK if you have the parameter names
In #included files
we have the functions prototypes only
implementations of function bodies are in libraries or in
other
cpp files
they are linked together