Chapter 3 ABSOLUTE C++ Function Basics WALTER SAVITCH SECOND EDITION PEARSON Copyright2006 Pearson Addison-Wesley All rights reserved
Chapter 3 Function Basics
Learning Objectives Predefined Functions Those that return a value and those that don't Programmer-defined Functions Defining,Declaring,Calling ◆Recursive Functions ◆Scope Rules ◆Local variables Global constants and global variables Blocks,nested scopes Copyright 2006 Pearson Addison-Wesley.All rights reserved. 3-2
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 3-2 Learning Objectives ¨ Predefined Functions ¨ Those that return a value and those that don’t ¨ Programmer-defined Functions ¨ Defining, Declaring, Calling ¨ Recursive Functions ¨ Scope Rules ¨ Local variables ¨ Global constants and global variables ¨ Blocks, nested scopes
Introduction to Functions Building Blocks of Programs Other terminology in other languages: Procedures,subprograms,methods ◆lnC++:functions ◆-PO Input-Process-Output Basic subparts to any program Use functions for these "pieces" Copyright006 Pearson Addison-Wesley.All rights reserved. 3-3
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 3-3 Introduction to Functions ¨ 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
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, <cmath>,<cstdlib>(Original "C"libraries) <iostream>(for cout,cin) Copyright 2006 Pearson Addison-Wesley.All rights reserved. 3-4
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 3-4 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., ¨<cmath> , <cstdlib> (Original "C" libraries) ¨<iostream> (for cout, cin)
Using Predefined Functions Math functions very plentiful Found in library <cmath.h> Most return a value (the "answer") Example:theRoot sqrt(9.0); ◆Components: sgrt name of library function theRoot variable used to assign "answer"to 9.0= argument or "starting input"for function ◆ln-P-O: ◆1=9.0 P="compute the square root" O=3,which is returned assigned to theRoot Copyright 2006 Pearson Addison-Wesley.All rights reserved. 3-5
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 3-5 Using Predefined Functions ¨ Math functions very plentiful ¨ Found in library <cmath.h> ¨ Most return a value (the "answer") ¨ Example: theRoot = sqrt(9.0); ¨ Components: sqrt = name of library function theRoot = variable used to assign "answer" to 9.0 = argument or "starting input" for function ¨ In I-P-O: ¨ I = 9.0 ¨ P = "compute the square root" ¨ O = 3, which is returned & assigned to theRoot