SlideShare a Scribd company logo
1 of 23
Download to read offline
© 2016 Cengage Learning®. May not be scanned, copied or
Introduction to Programming in C++
Eighth Edition
Lesson 9.1:
Value-Returning Functions
duplicated, or posted to a publicly accessible website, in whole
or in part.
• Raiseanumber to apower using the pow function
• Return the square root of anumber using thesqrt
function
• Generate random numbers
• Create and invoke afunction that returns avalue
• Passinformation by value to afunction
• Write afunction prototype
• Understand avariable’s scope and lifetime
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
2An Introduction to Programming with C++, Eighth Edition
Objectives
• Afunction is ablock of code that performs atask
• Every C++program contains at least one function
(main)
– Most contain manyfunctions
• Somefunctions are built-in functions (part ofC++):
defined in languagelibraries
• Others, called program-defined functions, arewritten
by programmers; defined in aprogram
• Functions allow for blocks of code to be used many
times in aprogram without having toduplicate code
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
3An Introduction to Programming with C++, Eighth Edition
Functions
• Functions also allow large, complex programs to be
broken down into small, manageablesub-tasks
• Eachsub-task is solved by afunction, and thus different
people can write different functions
• Many functions can then be combined intoasingle
program
• Typically, main is used to call other functions, but any
function can call any other function
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
4An Introduction to Programming with C++, Eighth Edition
Functions (cont’d.)
Figure 9-1 Illustrations of value-returning and void functions
Functions (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
5An Introduction to Programming with C++, Eighth Edition
• All functions are either value-returning orvoid
• All value-returning functions perform atask and then
return precisely onevalue
• In most cases,the value is returned to the statement
that called thefunction
• Typically, astatement that calls afunction assignsthe
return value to avariable
– However, areturn value could also be usedin a
comparison or calculation or could be printed to the
screen
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
6An Introduction to Programming with C++, Eighth Edition
Value-Returning Functions
• Thepow function is aconvenient tool to raise anumber
to apower (exponentiation)
• Thepow function raises anumber to apower and
returns the result asadouble number
• Syntax is pow(x, y), in which x is the base and y is the
exponent
• At least one of the twoarguments must be adouble
• Program must contain the #include <cmath>
directive to usethe powfunction
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
7An Introduction to Programming with C++, Eighth Edition
The pow Function
Figure 9-2 How to use the pow function
The pow Function (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
8An Introduction to Programming with C++, Eighth Edition
• sqrt function is abuilt-in value-returning function that
returns anumber’s square root asadouble
• Definition contained in cmathlibrary
–Program must contain #include <cmath>to useit
• Syntax: sqrt(x), in which x is a double or float
–Here, xis an actualargument, which is an item of
information afunction needs toperform its task
• Actual arguments are passed to afunction whencalled
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
9An Introduction to Programming with C++, Eighth Edition
The sqrt Function
Figure 9-3 How to use the sqrt function
The sqrt Function (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
10An Introduction to Programming with C++, Eighth Edition
• Program that calculates and displays the length ofa
right triangle hypotenuse
• Program usesPythagorean theorem
– Requires squaring and taking squareroot
• powfunction can be used to square
• sqrtfunction can be used to take square root
• Both are built-in value-returning functions
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
11An Introduction to Programming with C++, Eighth Edition
The Hypotenuse Program
Figure 9-4 Pythagorean theorem
The Hypotenuse Program (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
12An Introduction to Programming with C++, Eighth Edition
Figure 9-5 Problem specification, IPO chart information, and C++
instructions for the Hypotenuse Program
The Hypotenuse Program (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
13An Introduction to Programming with C++, Eighth Edition
Figure 9-6 Beginning of Hypotenuse program
The Hypotenuse Program (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
14An Introduction to Programming with C++, Eighth Edition
Figure 9-6 Completion of Hypotenuse Program and sample run
The Hypotenuse Program (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
15An Introduction to Programming with C++, Eighth Edition
• C++provides apseudo-random numbergenerator
– Producesasequence of numbers that meetcertain
statistical requirements forrandomness
– Numbers chosen uniformly from finite set of numbers
– Not truly random but sufficient for practical purposes
• Random number generator in C++:rand function
–Returns an integer between 0 and RAND_MAX, inclusive
– RAND_MAX is abuilt-in constant (>= 32767)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
16An Introduction to Programming with C++, Eighth Edition
The rand, srand, and time
Functions
• rand function’s syntax: rand()
– Doesn’t require any actual arguments, but parenthesesare
still required
• Expression:
lowerBound + rand() % (upperBound – lowerBound + 1)
– Allows ranges other than 0 to RAND_MAX to be used
– Rangeis upperBound to lowerBound
• Initialize random number generator eachtime
– Otherwise, will produce the samesequence
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
17An Introduction to Programming with C++, Eighth Edition
The rand, srand, and time
Functions (cont’d.)
Figure 9-7 How to use the rand function
The rand, srand, and time
Functions (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
18An Introduction to Programming with C++, Eighth Edition
Figure 9-8 How to generate random integers within a specific range
The rand, srand, and time
Functions (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
19An Introduction to Programming with C++, Eighth Edition
Figure 9-8 How to generate random integers within a specific range
The rand, srand, and time
Functions (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
20An Introduction to Programming with C++, Eighth Edition
• Use srand function (a void function) to initialize
random number generator
• Syntax: srand(seed), in which seed is an integer
actual argument that represents the starting point of
the generator
–Commonly initialized using the time function
• Ensuresunique sequence of numbers for eachprogram
run
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
21An Introduction to Programming with C++, Eighth Edition
The rand, srand, and time
Functions (cont’d.)
• time function is a value-returning function that
returns current time in number of seconds since
January 1, 1970
– Returns a time_t object, so must be cast to an integer
before passingto srand
– Program must contain #include <ctime> directive
to useit
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
22An Introduction to Programming with C++, Eighth Edition
The rand, srand, and time
Functions (cont’d.)
Figure 9-9 How to use the srand function
The rand, srand, and time
Functions (cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
23An Introduction to Programming with C++, Eighth Edition

More Related Content

What's hot

Chapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition StructureChapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition Structuremshellman
 
Chapter 4 - Completing the Problem-Solving Process
Chapter 4 - Completing the Problem-Solving ProcessChapter 4 - Completing the Problem-Solving Process
Chapter 4 - Completing the Problem-Solving Processmshellman
 
Chapter 5 - The Selection Structure
Chapter 5 - The Selection StructureChapter 5 - The Selection Structure
Chapter 5 - The Selection Structuremshellman
 
Chapter 3 - Variables and Constants
Chapter 3 - Variables and ConstantsChapter 3 - Variables and Constants
Chapter 3 - Variables and Constantsmshellman
 
Chapter 7 - The Repetition Structure
Chapter 7 - The Repetition StructureChapter 7 - The Repetition Structure
Chapter 7 - The Repetition Structuremshellman
 
Chapter 2 - Beginning the Problem-Solving Process
Chapter 2 - Beginning the Problem-Solving ProcessChapter 2 - Beginning the Problem-Solving Process
Chapter 2 - Beginning the Problem-Solving Processmshellman
 
Chapter 6 - More on the Selection Structure
Chapter 6 - More on the Selection StructureChapter 6 - More on the Selection Structure
Chapter 6 - More on the Selection Structuremshellman
 
test(3)arithmetic in c
test(3)arithmetic in ctest(3)arithmetic in c
test(3)arithmetic in cJaya Malathy
 

What's hot (20)

Chapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition StructureChapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition Structure
 
Chapter 4 - Completing the Problem-Solving Process
Chapter 4 - Completing the Problem-Solving ProcessChapter 4 - Completing the Problem-Solving Process
Chapter 4 - Completing the Problem-Solving Process
 
Chapter 5 - The Selection Structure
Chapter 5 - The Selection StructureChapter 5 - The Selection Structure
Chapter 5 - The Selection Structure
 
Chapter 3 - Variables and Constants
Chapter 3 - Variables and ConstantsChapter 3 - Variables and Constants
Chapter 3 - Variables and Constants
 
Chapter 7 - The Repetition Structure
Chapter 7 - The Repetition StructureChapter 7 - The Repetition Structure
Chapter 7 - The Repetition Structure
 
Lesson 1 introduction to programming
Lesson 1 introduction to programmingLesson 1 introduction to programming
Lesson 1 introduction to programming
 
Chapter 2 - Beginning the Problem-Solving Process
Chapter 2 - Beginning the Problem-Solving ProcessChapter 2 - Beginning the Problem-Solving Process
Chapter 2 - Beginning the Problem-Solving Process
 
Chapter 6 - More on the Selection Structure
Chapter 6 - More on the Selection StructureChapter 6 - More on the Selection Structure
Chapter 6 - More on the Selection Structure
 
Lesson 5.2 logical operators
Lesson 5.2 logical operatorsLesson 5.2 logical operators
Lesson 5.2 logical operators
 
Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
 
Lesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th stepLesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th step
 
Lesson 3.1 variables and constant
Lesson 3.1 variables and constantLesson 3.1 variables and constant
Lesson 3.1 variables and constant
 
Lesson 5 .1 selection structure
Lesson 5 .1 selection structureLesson 5 .1 selection structure
Lesson 5 .1 selection structure
 
Lesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving processLesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving process
 
Lesson 13 object and class
Lesson 13 object and classLesson 13 object and class
Lesson 13 object and class
 
Mechatronics engineer
Mechatronics engineerMechatronics engineer
Mechatronics engineer
 
test(3)arithmetic in c
test(3)arithmetic in ctest(3)arithmetic in c
test(3)arithmetic in c
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Lesson 3.2 data types for memory location
Lesson 3.2 data types for memory locationLesson 3.2 data types for memory location
Lesson 3.2 data types for memory location
 
Chapter 02 - Problem Solving
Chapter 02 - Problem SolvingChapter 02 - Problem Solving
Chapter 02 - Problem Solving
 

Similar to Lesson 9.1 value returning

Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)Kamran Zafar
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programmingmshellman
 
chapter4.ppt
chapter4.pptchapter4.ppt
chapter4.pptMalathyN6
 
JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...
JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...
JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...David Taieb
 
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016Andrew Richards
 
Node.js Deeper Dive
Node.js Deeper DiveNode.js Deeper Dive
Node.js Deeper DiveJustin Reock
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Thomas Wuerthinger
 
DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....
DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....
DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....at315244
 
Петро Коренєв, "Presentation state containers"
Петро Коренєв, "Presentation state containers"Петро Коренєв, "Presentation state containers"
Петро Коренєв, "Presentation state containers"Sigma Software
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience App Ttrainers .com
 
A intro to (hosted) Shiny Apps
A intro to (hosted) Shiny AppsA intro to (hosted) Shiny Apps
A intro to (hosted) Shiny AppsDaniel Koller
 
DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...
DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...
DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...Gene Kim
 
Accelerate Go-To-Market Speed in a CI/CD Environment
Accelerate Go-To-Market Speed in a CI/CD EnvironmentAccelerate Go-To-Market Speed in a CI/CD Environment
Accelerate Go-To-Market Speed in a CI/CD EnvironmentAmazon Web Services
 
Fraud Detection in Financial Services using Graph Analysis and Machine Learning
Fraud Detection in Financial Services using Graph Analysis and Machine LearningFraud Detection in Financial Services using Graph Analysis and Machine Learning
Fraud Detection in Financial Services using Graph Analysis and Machine LearningThomas Teske
 
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016MLconf
 

Similar to Lesson 9.1 value returning (20)

Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programming
 
Sql9e ppt ch08
Sql9e ppt ch08Sql9e ppt ch08
Sql9e ppt ch08
 
chapter4.ppt
chapter4.pptchapter4.ppt
chapter4.ppt
 
Duel of Two Libraries: Cairo & Skia
Duel of Two Libraries: Cairo & SkiaDuel of Two Libraries: Cairo & Skia
Duel of Two Libraries: Cairo & Skia
 
JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...
JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...
JavaOne 2016: Getting Started with Apache Spark: Use Scala, Java, Python, or ...
 
Open mp
Open mpOpen mp
Open mp
 
Mechatronics engineer
Mechatronics engineerMechatronics engineer
Mechatronics engineer
 
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
 
Node.js Deeper Dive
Node.js Deeper DiveNode.js Deeper Dive
Node.js Deeper Dive
 
Eclipse - Single Source;Three Runtimes
Eclipse - Single Source;Three RuntimesEclipse - Single Source;Three Runtimes
Eclipse - Single Source;Three Runtimes
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
 
DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....
DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....
DC16_Ch09_Operating Systems Managing, Coordinating, and Monitoring Resources....
 
Петро Коренєв, "Presentation state containers"
Петро Коренєв, "Presentation state containers"Петро Коренєв, "Presentation state containers"
Петро Коренєв, "Presentation state containers"
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
A intro to (hosted) Shiny Apps
A intro to (hosted) Shiny AppsA intro to (hosted) Shiny Apps
A intro to (hosted) Shiny Apps
 
DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...
DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...
DOES16 San Francisco - Marc Ng - SAP’s DevOps Journey: From Building an App t...
 
Accelerate Go-To-Market Speed in a CI/CD Environment
Accelerate Go-To-Market Speed in a CI/CD EnvironmentAccelerate Go-To-Market Speed in a CI/CD Environment
Accelerate Go-To-Market Speed in a CI/CD Environment
 
Fraud Detection in Financial Services using Graph Analysis and Machine Learning
Fraud Detection in Financial Services using Graph Analysis and Machine LearningFraud Detection in Financial Services using Graph Analysis and Machine Learning
Fraud Detection in Financial Services using Graph Analysis and Machine Learning
 
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
Tom Peters, Software Engineer, Ufora at MLconf ATL 2016
 

More from MLG College of Learning, Inc (20)

PC111.Lesson2
PC111.Lesson2PC111.Lesson2
PC111.Lesson2
 
PC111.Lesson1
PC111.Lesson1PC111.Lesson1
PC111.Lesson1
 
PC111-lesson1.pptx
PC111-lesson1.pptxPC111-lesson1.pptx
PC111-lesson1.pptx
 
PC LEESOON 6.pptx
PC LEESOON 6.pptxPC LEESOON 6.pptx
PC LEESOON 6.pptx
 
PC 106 PPT-09.pptx
PC 106 PPT-09.pptxPC 106 PPT-09.pptx
PC 106 PPT-09.pptx
 
PC 106 PPT-07
PC 106 PPT-07PC 106 PPT-07
PC 106 PPT-07
 
PC 106 PPT-01
PC 106 PPT-01PC 106 PPT-01
PC 106 PPT-01
 
PC 106 PPT-06
PC 106 PPT-06PC 106 PPT-06
PC 106 PPT-06
 
PC 106 PPT-05
PC 106 PPT-05PC 106 PPT-05
PC 106 PPT-05
 
PC 106 Slide 04
PC 106 Slide 04PC 106 Slide 04
PC 106 Slide 04
 
PC 106 Slide no.02
PC 106 Slide no.02PC 106 Slide no.02
PC 106 Slide no.02
 
pc-106-slide-3
pc-106-slide-3pc-106-slide-3
pc-106-slide-3
 
PC 106 Slide 2
PC 106 Slide 2PC 106 Slide 2
PC 106 Slide 2
 
PC 106 Slide 1.pptx
PC 106 Slide 1.pptxPC 106 Slide 1.pptx
PC 106 Slide 1.pptx
 
Db2 characteristics of db ms
Db2 characteristics of db msDb2 characteristics of db ms
Db2 characteristics of db ms
 
Db1 introduction
Db1 introductionDb1 introduction
Db1 introduction
 
Lesson 3.2
Lesson 3.2Lesson 3.2
Lesson 3.2
 
Lesson 3.1
Lesson 3.1Lesson 3.1
Lesson 3.1
 
Lesson 1.6
Lesson 1.6Lesson 1.6
Lesson 1.6
 
Lesson 3.2
Lesson 3.2Lesson 3.2
Lesson 3.2
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Lesson 9.1 value returning

  • 1. © 2016 Cengage Learning®. May not be scanned, copied or Introduction to Programming in C++ Eighth Edition Lesson 9.1: Value-Returning Functions duplicated, or posted to a publicly accessible website, in whole or in part.
  • 2. • Raiseanumber to apower using the pow function • Return the square root of anumber using thesqrt function • Generate random numbers • Create and invoke afunction that returns avalue • Passinformation by value to afunction • Write afunction prototype • Understand avariable’s scope and lifetime © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 2An Introduction to Programming with C++, Eighth Edition Objectives
  • 3. • Afunction is ablock of code that performs atask • Every C++program contains at least one function (main) – Most contain manyfunctions • Somefunctions are built-in functions (part ofC++): defined in languagelibraries • Others, called program-defined functions, arewritten by programmers; defined in aprogram • Functions allow for blocks of code to be used many times in aprogram without having toduplicate code © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 3An Introduction to Programming with C++, Eighth Edition Functions
  • 4. • Functions also allow large, complex programs to be broken down into small, manageablesub-tasks • Eachsub-task is solved by afunction, and thus different people can write different functions • Many functions can then be combined intoasingle program • Typically, main is used to call other functions, but any function can call any other function © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 4An Introduction to Programming with C++, Eighth Edition Functions (cont’d.)
  • 5. Figure 9-1 Illustrations of value-returning and void functions Functions (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 5An Introduction to Programming with C++, Eighth Edition
  • 6. • All functions are either value-returning orvoid • All value-returning functions perform atask and then return precisely onevalue • In most cases,the value is returned to the statement that called thefunction • Typically, astatement that calls afunction assignsthe return value to avariable – However, areturn value could also be usedin a comparison or calculation or could be printed to the screen © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 6An Introduction to Programming with C++, Eighth Edition Value-Returning Functions
  • 7. • Thepow function is aconvenient tool to raise anumber to apower (exponentiation) • Thepow function raises anumber to apower and returns the result asadouble number • Syntax is pow(x, y), in which x is the base and y is the exponent • At least one of the twoarguments must be adouble • Program must contain the #include <cmath> directive to usethe powfunction © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 7An Introduction to Programming with C++, Eighth Edition The pow Function
  • 8. Figure 9-2 How to use the pow function The pow Function (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 8An Introduction to Programming with C++, Eighth Edition
  • 9. • sqrt function is abuilt-in value-returning function that returns anumber’s square root asadouble • Definition contained in cmathlibrary –Program must contain #include <cmath>to useit • Syntax: sqrt(x), in which x is a double or float –Here, xis an actualargument, which is an item of information afunction needs toperform its task • Actual arguments are passed to afunction whencalled © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 9An Introduction to Programming with C++, Eighth Edition The sqrt Function
  • 10. Figure 9-3 How to use the sqrt function The sqrt Function (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 10An Introduction to Programming with C++, Eighth Edition
  • 11. • Program that calculates and displays the length ofa right triangle hypotenuse • Program usesPythagorean theorem – Requires squaring and taking squareroot • powfunction can be used to square • sqrtfunction can be used to take square root • Both are built-in value-returning functions © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 11An Introduction to Programming with C++, Eighth Edition The Hypotenuse Program
  • 12. Figure 9-4 Pythagorean theorem The Hypotenuse Program (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12An Introduction to Programming with C++, Eighth Edition
  • 13. Figure 9-5 Problem specification, IPO chart information, and C++ instructions for the Hypotenuse Program The Hypotenuse Program (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 13An Introduction to Programming with C++, Eighth Edition
  • 14. Figure 9-6 Beginning of Hypotenuse program The Hypotenuse Program (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 14An Introduction to Programming with C++, Eighth Edition
  • 15. Figure 9-6 Completion of Hypotenuse Program and sample run The Hypotenuse Program (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 15An Introduction to Programming with C++, Eighth Edition
  • 16. • C++provides apseudo-random numbergenerator – Producesasequence of numbers that meetcertain statistical requirements forrandomness – Numbers chosen uniformly from finite set of numbers – Not truly random but sufficient for practical purposes • Random number generator in C++:rand function –Returns an integer between 0 and RAND_MAX, inclusive – RAND_MAX is abuilt-in constant (>= 32767) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 16An Introduction to Programming with C++, Eighth Edition The rand, srand, and time Functions
  • 17. • rand function’s syntax: rand() – Doesn’t require any actual arguments, but parenthesesare still required • Expression: lowerBound + rand() % (upperBound – lowerBound + 1) – Allows ranges other than 0 to RAND_MAX to be used – Rangeis upperBound to lowerBound • Initialize random number generator eachtime – Otherwise, will produce the samesequence © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 17An Introduction to Programming with C++, Eighth Edition The rand, srand, and time Functions (cont’d.)
  • 18. Figure 9-7 How to use the rand function The rand, srand, and time Functions (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 18An Introduction to Programming with C++, Eighth Edition
  • 19. Figure 9-8 How to generate random integers within a specific range The rand, srand, and time Functions (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 19An Introduction to Programming with C++, Eighth Edition
  • 20. Figure 9-8 How to generate random integers within a specific range The rand, srand, and time Functions (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 20An Introduction to Programming with C++, Eighth Edition
  • 21. • Use srand function (a void function) to initialize random number generator • Syntax: srand(seed), in which seed is an integer actual argument that represents the starting point of the generator –Commonly initialized using the time function • Ensuresunique sequence of numbers for eachprogram run © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 21An Introduction to Programming with C++, Eighth Edition The rand, srand, and time Functions (cont’d.)
  • 22. • time function is a value-returning function that returns current time in number of seconds since January 1, 1970 – Returns a time_t object, so must be cast to an integer before passingto srand – Program must contain #include <ctime> directive to useit © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 22An Introduction to Programming with C++, Eighth Edition The rand, srand, and time Functions (cont’d.)
  • 23. Figure 9-9 How to use the srand function The rand, srand, and time Functions (cont’d.) © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 23An Introduction to Programming with C++, Eighth Edition