• No results found

Lec5 - Functions (I).pdf

N/A
N/A
Protected

Academic year: 2020

Share "Lec5 - Functions (I).pdf"

Copied!
16
0
0

Loading.... (view fulltext now)

Full text

(1)

Structured Programming

Using C++

Lecture 5 : Function Basics

Dr. Amal Khalifa

Lecture Contents:

Predefined Functions

Those that return a value and those that don’t

Programmer-defined Functions

Defining, Declaring, Calling

Recursive Functions

Scope Rules

Local variables

(2)

Introduction to Functions

3

Building Blocks of Programs

Other terminology in other languages:

Procedures, subprograms, methods

In C++: functions

I-P-O

Input – Process – Output

Basic subparts to any program

Use functions for these "pieces"

Dr. Amal Khalifa, 2012

Predefined Functions

Libraries full of functions for our use!

Two types:

Those that return a value

Those that do not (void)

Must "#include" appropriate library

e.g.,

(3)

Using Predefined Functions

5

Math functions very plentiful

Found in library <cmath.h>

Most return a value (the "answer")

Example:

theRoot = sqrt(9.0);

• I = 9.0  argument/parameter (literal/variable,/expression) • P = sqrt()  function call

• O = 3  return value

The call itself can be part of an expression:

 bonus = sqrt(sales)/10;

 A function call is allowed wherever it’s legal to use an expression of the function’s return type

Dr. Amal Khalifa, 2012

(4)

Example :

Predefined Functions (2 of 2)

7 Dr. Amal Khalifa, 2012

(5)

More Math Functions

(2 of 2)

Dr. Amal Khalifa, 2012 9

Case study: Random Numbers

Used for simulations, games

rand()

 Takes no arguments

 Returns a "randomly chosen" value between 0 & RAND_MAX

Scaling:

rand() % 6

 Random value between 0 & 5  Squeezes the range

Shifting:

rand() % 6 + 1

 Shifts range between 1 & 6 (e.g., die roll)

Use srand(seed_value);

 Alter sequence of generated numbers  Can use system time in Library <time>

(6)

Random Examples

Dr. Amal Khalifa, 2012

11

Random double between 0.0 & 1.0:

(RAND_MAX – rand())/static_cast<double>(RAND_MAX)

Type cast used to force double-precision division

Random int between 1 & 6:

rand() % 6 + 1

"%" is modulus operator (remainder)

Random int between 10 & 20:

rand() % 10 + 10

Predefined void Functions

No returned value

Performs an action, but sends no "answer"

When called, it’s a statement itself

exit(1); // No return value, so not assigned

 This call terminates program

 void functions can still have arguments

All aspects same as functions that "return a value"

(7)

User defined Functions

A detailed look..

Programmer-Defined Functions

Write your own functions!

Building blocks of programs

Divide & Conquer

Readability

Re-use

Your "definition" can go in either:

Same file as main()

(8)

Components of Function Use

15

3 Pieces to using functions:

Function Declaration/prototype

 Information for compiler to properly interpret calls

Function Definition

 Actual implementation/code for what function does

Function Call

 Transfer control to function

Dr. Amal Khalifa, 2012

Function Declaration

Also called function prototoype

Tells compiler how to interpret calls

 Return type  Function name  Parameter list

Syntax:

<return_type> FnName(<formal-parameter-list>);

Placed before any calls

(9)

Function Definition

17

Implementation of function

Placed after function main()

Functions are "equals"; no function is ever "part" of

another

Formal parameters in definition

return statement:

 Transfers control back to "calling" function

 Typically the LAST statement in function definition

Dr. Amal Khalifa, 2012

Function Call

Just like calling predefined function

<variable> = FnName(<actual-parameter-list>);

Return value??

Arguments??

often called "actual arguments"

(10)

Example : the Cost Function

Dr. Amal Khalifa, 2012 19

Write a function that computes the total cost of a

number of items including sales tax. Test the function in

a program.

Hint: assume that the sales tax rate is 5%.

(11)

21

Ex

ampl

e

:

t

he

C

ost

Fu

nct

io

n

Alternative Function Declaration

Recall: Function declaration is "information"

for compiler

Compiler only needs to know:

 Return type  Function name  Parameter list

Formal parameter names not needed:

double totalCost(int, double);

Still "should" put in formal parameter names

(12)

Example

Dr. Amal Khalifa, 2012 23

Write a function

integerPower(base, exponent)

that

returns the value of:

base

power

Functions Calling Functions

We’re already doing this!

main() is a function!

One and only one main() exists in a program

 Should return "int" or "void"  Who is the caller??

(13)

Example

Dr. Amal Khalifa, 2012 25

Write a function that rounds a number to the nearest integer

number.

Hint: Use floor(num+0.5)

Boolean Return-Type Functions

Return-type can be any valid type

bool appropriate(int rate); //declaration

bool appropriate (int rate) //definition

{

return (((rate>=10)&&(rate<20))||(rate==0); }

if (appropriate(entered_rate)) //call cout << "Rate is valid\n";

(14)

More Examples

Dr. Amal Khalifa, 2012 27

Write a function

isOdd(number)

to determine if a given

number is odd or not.

Write a function

isMultiple ,

for a pair of integers , that

determines whether the second integer is a multiple of the first.

Hint: use the remainder operator (%)

Declaring “void” Functions

Similar to functions returning a value

Return type specified as "void"

Example:

//declaration..

void showResults(double fDegrees, double cDegrees);

//definition...

void showResults(double fDegrees, double cDegrees) {

cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1);

cout << fDegrees

<< " degrees fahrenheit equals \n" << cDegrees << " degrees celsius.\n";

(15)

Example:

use of return in void functions

Dr. Amal Khalifa, 2012 29

Write a function that outputs

the instructions for dividing a

given amount of ice-cream

among people at a table.

Be careful with the case where

there are no people at the table

(division by zero)

Example:

(16)

Dr. Amal Khalifa, 2012 31

That’s all for today !!

References

Related documents

To counteract these structural variations, facilitate fabric handle, garment making and to incorporate print designs and laser etching, the bark cloth was fused with a

BRIEF DESCRIPTION OF PROJECT APPROVED FOR COLLECTION AND USE: Rehabilitate runway 1/19 and runway safety area, phase I Snow removal equipment.. Crack seal

Although there are numerous books on the science of pharmaceutics and dosage form design, those books cover different areas of the discipline and do not provide an

Wall Climbing And Pipe Crawler Robots For Nozzle Weld Inspection Inside Nuclear Pressure

preferred represent bias scores calculated from the observers gaze. Bias scores represent the average viewing time of the non-preferred subtracted from the preferred viewing time.

recently, there wasn’t a strong need for CenturyLink to add that feature for the Globe area. CenturyLink will be updating its equipment as will the County, which will enable caller

Resolved, the House of _____ concurring, That the 78th General Convention direct that the 2004 Model Policies developed by The Church Insurance Agency Corporation for

Ownership of both the online renewal licence in to apply online, prescribed fee charged by delhi pharmacy council depending on sale of drug licence plays an appropriate