Sei sulla pagina 1di 42

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 (Chapter 2 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
Without function

With function

#include <iostream>
using namespace std;

#include <iostream>
using namespace std;

/* traditional first
program */

/* traditional first
program */

int main()
{
cout << "Hello world"
<< endl;
return 0;
}

void Hello()
{
cout << "Hello world"
<< endl;
}
int main()
{
Hello();
return 0;
}

Syntax of Functions
 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 variables
statements
}
 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 for Functions


#include <iostream>
using namespace std;

void Hello()
{
cout << "Hello world"
<< endl;
}
int main()
{
Hello();
return 0;
}

return-type function-name(parameters)
{
local-variables
statements
}

void means returns nothing.


no parameters (we will see
parametric functions today)
no local variables

Drawing Head Without functions


#include <iostream>
using namespace std;
int main()
{
cout << " |||||||||||||||| "
cout << " |
| "
cout << " |
o
o
| "
cout << " _|
|_ "
cout << "|_
_|"
cout << " |
|______|
| "
cout << " |
| "
return 0;
}

<<
<<
<<
<<
<<
<<
<<

endl;
endl;
endl;
endl;
endl;
endl;
endl;

 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 

Drawing Head With functions


parts.cpp
#include <iostream>
using namespace std;
// functions appear here
int main()
{
Hair();
Sides();
Eyes(); Ears(); Smile();
Sides();
return 0;
}

 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

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 variables


type name
Example: float radius
return-type func-name(type param1,,type param<n>)
{
local variables
statements
}

Area calculation with parameterized function


#include <iostream>
using namespace std;
// area calculation program that employs functions
void calculate_area(float radius)
{
float area;
area = 3.14 * radius * radius;
cout << "The area of a circle with radius " << radius << " is "
<< area << endl;
}
int main()
{
float r;
r = 3;
calculate_area(r);
calculate_area(2.5);
calculate_area(r / 2);
return 0;
}

Area calculation with parameterized function


#include <iostream>
using namespace std;
// area calculation program that employs functions
void calculate_area (float radius)
{
radius
float area;

is 3

area = 3.14 * radius * radius;


cout << "The area of a circle with radius " << radius << " is "
<< area << endl;
}
int main()
{
float r;
r = 3;
calculate_area(r);
calculate_area(2.5);
calculate_area(r / 2);
return 0;
}

Output Screen
The area of a circle with radius 3 is 28.26

Area calculation with parameterized function


#include <iostream>
using namespace std;
// area calculation program that employs functions
void calculate_area (float radius)
{
radius
float area;

is 2.5

area = 3.14 * radius * radius;


cout << "The area of a circle with radius " << radius << " is "
<< area << endl;
}
int main()
{
float r;
r = 3;
calculate_area(r);
calculate_area(2.5);
calculate_area(r / 2);
return 0;
}

Output Screen
The area of a circle with radius 3 is 28.26
The area of a circle with radius 2.5 is 19.625

Area calculation with parameterized function


#include <iostream>
using namespace std;
// area calculation program that employs functions
void calculate_area (float radius)
{
radius
float area;

is 1.5

area = 3.14*radius*radius;
cout << "The area of a circle with radius " << radius << " is "
<< area << endl;
}

Output Screen

int main()
{
float r;
r = 3;
calculate_area(r);
calculate_area(2.5);
calculate_area(r / 2);
return 0;
}

The area of a circle with radius 3 is 28.26


The area of a circle with radius 2.5 is 19.625
The area of a circle with radius 1.5 is 7.065

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 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 McDonald
McDonalds Farm
(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: sheep
Enter noise that a sheep makes: baah
Old 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 here
And a baah baah there
Here a baah, there a baah, everywhere a baah baah
Old 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;
string noise;

// variable for name of animal


// variable for noise it makes

cout << "Enter the name of an animal: ";


cin >> animal;
cout << "Enter noise that a " << animal << " makes: ";
cin >> noise;
Verse(animal,noise);
return 0;
}

Analysis of the Run


1. 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 << "enter animal ";
cin >> animal;
cout << "enter noise a " << animal << " makes ";
cin >> noise;
}
 Just before the first place theyre used:

{
cout << "enter animal ";
string animal;
cin >> animal;
cout << "enter noise a " << animal << " makes ";
string noise;
cin >> noise;
}

Where to define variables


 NO GLOBAL VARIABLES
 A global variable is a variable defined outside the function bodies
#include <iostream>
using namespace std;
int global_number;
int main()
{
cout << "Hello world << endl;
return 0;
}

 They can be used in all functions without definition


 That is why it is the #1 enemy of parameters
 If you use global variables, you violate the independence property of

functions and may lose your control in big programs


 Thus, IT IS FORBIDDEN TO USE GLOBAL VARIABLES
 If you use a global variable in hw and exams, your grade is reduced!
 We will revisit the global variable concept towards the end of the
course.

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 declaration
int 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 << circlearea(12) << endl;
if (circlearea(r/2) >= 100)
{
cout << large circle << endl;
}
circlearea(r);

//syntax ok, but meaningless because


//function call returned value is not used.

Math library functions


 Mathematical functions like square root, logarithm, sin, cos, etc.
 Prototypes are in header file cmath
#include <cmath>
 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


Function Syntax
return-type func-name(parameters)
{
local variables
statements
}
Example: Function to calculate volume of a sphere

function body

double SphereVol(double radius)


{
return 4.0*radius*radius*radius*acos(-1)/3;
}

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 from

function, 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


 A program piece that uses that function

string WeekDay(int day)


// precondition: 0 <= day <= 6
// postcondition: return "Sunday" for 0,
//
//
{
if (0 == day)
else if (1 ==
else if (2 ==
else if (3 ==
else if (4 ==
else if (5 ==
else if (6 ==
}

"Monday" for 1,

"Saturday" for 6

return "Sunday";
day) return "Monday";
day) return "Tuesday";
day) return "Wednesday";
day) return "Thursday";
day) return "Friday";
day) return "Saturday";

string dayName;
int
dayNum;
cout << " enter day (0-6): ";
cin >> dayNum;
dayName = WeekDay(dayNum);
 Which is/are correct use of WeekDay

function? Why?
cout << WeekDay(5) << endl;
int j = WeekDay(0);
cout << WeekDay(2.1) << endl;
string s = WeekDay(22);
WeekDay(3);

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 function
bool IsLeapYear(int year);
// pre: year > 0
// post: return true if year is a leap year

Implementation and use of leap year function


bool 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;
See
}
isleap.cpp
int main()
{
int year;
cout << "enter a year ";
cin >> year;
if (IsLeapYear(year))
{
cout << year << " has 366 days, it is a leap year" << endl;
}
else
{
cout << year << " has 365 days, it is NOT a leap year" << endl;
}
return 0;
}

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 << Hello << name << endl;
}

 Like variables, a function must be declared before its

first call
 Problem of function declaration order
 You cannot call a function before you declare it

 SOLUTION: You may define function prototypes (a copy of

the heading) at the beginning without function declarations

Function Prototype Example Problem


 What is the problem below (program order.cpp) ?
void Hi (string name)
{
cout << "Hi " << name << endl;
Greetings();
}
void Greetings()
{
cout << "Things are happening inside this computer" << endl;
}
int main()
{
Hi("Fred");
return 0;
}

 Greetings() is called in Hi() but it is declared afterwards

Function Prototype Solution


 Add function prototypes to the beginning (order2.cpp)
#include <iostream>
#include <string>
using namespace std;
void Hi(string);
void Greetings();

Function
Declarations

Prototypes

void Hi (string name)


{
cout << "Hi " << name << endl;
Greetings();
}
void Greetings()
{
cout << "Things are happening inside this computer"
<< endl;
}
int main()
{
Hi("Fred");
return 0;
}

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