40
An Introduction to Programming with C++ Fifth Edition Chapter 9 Value-Returning Functions

An Introduction to Programming with C++ Fifth Edition Chapter 9 Value-Returning Functions

  • View
    216

  • Download
    0

Embed Size (px)

Citation preview

An Introduction to Programming with C++

Fifth Edition

Chapter 9Value-Returning Functions

An Introduction to Programming with C++, Fifth Edition 2

Objectives

• Raise a number to a power

• Generate random numbers

• Create and invoke a function that returns a value

• Pass information, by value, to a function

An Introduction to Programming with C++, Fifth Edition 3

Objectives (continued)

• Write a function prototype

• Understand a variable’s scope and lifetime

• Use the .NET C++ Math::Pow() method

• Generate random integers in .NET C++

An Introduction to Programming with C++, Fifth Edition 4

Concept Lesson

• Functions

• Value-Returning Functions

• Raising a Number to a Power

• Generating Random Numbers

• Creating Program-Defined Value-Returning Functions

• Processing a Function

An Introduction to Programming with C++, Fifth Edition 5

Functions

• A function is a block of code that performs a task

• A C++ program contains at least one function: main()– Most contain many more

• Programmers use functions because they:– Allow programmer to avoid duplicating code– Allow programs to be broken into manageable tasks

• Functions can be categorized into:– Value-returning functions– Void functions

An Introduction to Programming with C++, Fifth Edition 6

Value-Returning Functions

• A value-returning function returns precisely one value after completing its assigned task– Usually returned to the statement that called function

• Typically, statement displays return value, uses it in a calculation, or assigns it to a variable

– Some value-returning functions are built into C++• E.g., getline() and toupper()

An Introduction to Programming with C++, Fifth Edition 7

Raising a Number to a Power

• You use pow( )to raise a number to a power and return result as a double number

An Introduction to Programming with C++, Fifth Edition 8

Generating Random Numbers

• A pseudo-random number generator produces a sequence of numbers that meet certain statistical requirements for randomness– Numbers are chosen with equal probability from a

finite set of numbers– Chosen numbers are sufficiently random for practical

purposes

• rand() returns an integer greater than or equal to zero and less than or equal to RAND_MAX– RAND_MAX is always at least 32,767

An Introduction to Programming with C++, Fifth Edition 9

Generating Random Numbers (continued)

Generating Random Numbers (continued)

An Introduction to Programming with C++, Fifth Edition 10

An Introduction to Programming with C++, Fifth Edition 11

Generating Random Numbers (continued)

An Introduction to Programming with C++, Fifth Edition 12

Generating Random Numbers (continued)

An Introduction to Programming with C++, Fifth Edition 13

Generating Random Numbers (continued)

• You should initialize the random number generator in each program in which it is used– Otherwise, it will generate the same series of

numbers each time– Use the srand() function

• You must provide a seed

– Integer that represents the starting point for the random number generator

– Usually use time(): returns current time as seconds elapsed since midnight January 1, 1970

An Introduction to Programming with C++, Fifth Edition 14

Generating Random Numbers (continued)

An Introduction to Programming with C++, Fifth Edition 15

Random Numbers Program: Displaying Random Addition Problems• Program displays five random addition problems on

the screen– After displaying an addition problem, it allows user to

enter the answer to the problem– It checks whether the user’s answer is correct

• “Correct!”

• “Sorry, the sum is X”

An Introduction to Programming with C++, Fifth Edition 16

Random Numbers Program: Displaying Random Addition Problems (continued)

An Introduction to Programming with C++, Fifth Edition 17

Random Numbers Program: Displaying Random Addition Problems (continued)

An Introduction to Programming with C++, Fifth Edition 18

Random Numbers Program: Displaying Random Addition Problems

(continued)

An Introduction to Programming with C++, Fifth Edition 19

Creating Program-DefinedValue-Returning Functions

• You can create your own value-returning functions – Program-defined functions

• A function definition is composed of:– Function header– Function body

An Introduction to Programming with C++, Fifth Edition 20

Creating Program-DefinedValue-Returning Functions (continued)

An Introduction to Programming with C++, Fifth Edition 21

Function Header

• Function header: first line in a function definition – Does not end with a semicolon

• Not considered a C++ statement

– Begins with returnDataType

– Next comes the name of the function• Naming rules are the same as for naming variables

• Name usually begins with a verb

– Also has an optional parameterList enclosed in ()• Lists data type and name of formal parameters

– Formal parameters store the information passed to the function when it is invoked

An Introduction to Programming with C++, Fifth Edition 22

Passing Information to a Function

• Items passed to a function are actual arguments– Can be a variable, named constant, literal constant,

or keyword• You can pass a variable:

– by value (a copy of the value is passed), or

– by reference (the variable address is passed)

– Examples• calcRectangleArea(2, 3)• calcRectangleArea(length, width)

default

pass by value

An Introduction to Programming with C++, Fifth Edition 23

Function Body

• Function body contains instructions the function follows to perform its assigned task– Begins with { and ends with }– The last statement is usually return expression;

• expression represents the value the function returns to the statement that called it

– return statement alerts computer that the function has completed its task

• Data type of expression must agree with the returnDataType specified in function header

An Introduction to Programming with C++, Fifth Edition 24

Using a Function Prototype

• If a function definition appears below main(), you must enter a function prototype above main()– Prototype specifies function’s name, data type of

return value and of each formal parameter

– Usually after #includes and usings

An Introduction to Programming with C++, Fifth Edition 25

Processing a Function

• When the computer processes a statement containing a program-defined function:1. It locates the function’s code

2. Passes values of actual arguments to function

3. Function receives values and stores them in the memory locations listed in its parameterList

4. Function code is processed

5. Return value is returned to calling function

An Introduction to Programming with C++, Fifth Edition 26

Processing a Function (continued)

An Introduction to Programming with C++, Fifth Edition 27

Processing a Function (continued)

An Introduction to Programming with C++, Fifth Edition 28

Processing a Function (continued)

Processing a Function (continued)

29An Introduction to Programming with C++, Fifth Edition

An Introduction to Programming with C++, Fifth Edition 30

The Scope and Lifetime of a Variable

• A variable’s scope indicates where in the program it can be used– Local or global

• Local variables are declared within a function or appear in a function’s parameterList

• Global variables are declared outside of any function and remain in memory until program ends

– Avoid using global variables in your programs

• A variable’s lifetime indicates how long it remains in memory

An Introduction to Programming with C++, Fifth Edition 31

The Bonus Calculation Program

• Program calculates and displays a 5% bonus amount– Based on the amount of sales entered by the user

• Program uses two value-returning functions:– getSales()– calcBonus()

An Introduction to Programming with C++, Fifth Edition 32

The Bonus Calculation Program (continued)

An Introduction to Programming with C++, Fifth Edition 33

The Bonus Calculation Program (continued)

An Introduction to Programming with C++, Fifth Edition 34

The Bonus Calculation Program (continued)

An Introduction to Programming with C++, Fifth Edition 35

The Bonus Calculation Program (continued)

The Bonus Calculation Program (continued)

An Introduction to Programming with C++, Fifth Edition 36

An Introduction to Programming with C++, Fifth Edition 37

The Bonus Calculation Program (continued)

An Introduction to Programming with C++, Fifth Edition 38

Summary

• Programmers use functions because they:– Allow programmer to avoid duplicating code – Allow programs to be broken into manageable tasks

• Functions can be value-returning or void– E.g., pow() and rand() are value-returning functions

• A function definition has a function header and a body– Header specifies return data type, function name, and

(optional) parameterList enclosed in parentheses– By default, variables are passed to a function by value

An Introduction to Programming with C++, Fifth Edition 39

Summary (continued)

• The function body contains instructions for a task– Enclosed in braces

• You must include a function prototype for each function defined below main()

• A variable’s scope can be either local or global – Indicates where in a program a variable can be used

• If multiple memory locations have same name, and it appears in a statement, the computer uses the position of the statement within the program to determine which memory location to use

An Introduction to Programming with C++, Fifth Edition 40

Application Lesson: Using Value-Returning Functions in a C++ Program• Lab 9.1: Stop and Analyze

• Lab 9.2:– Create a program to calculate and display the

monthly payments of a loan

• Lab 9.3:– Modified program should allow user to enter interest

rates either as a whole or as a decimal number

• Lab 9.4: Desk-Check Lab

• Lab 9.5: Debugging Lab