Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Modular Programming With Functions
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
An Introduction to Programming with C++ Fifth Edition
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
C++ for Engineers and Scientists Third Edition
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
+ Storage Classes and Linkage. + Introduction Scope describe the region or regions of a program that can access and identifier Variables can be shared.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
Functions.
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
Functions and an Introduction to Recursion
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
6 Chapter Functions.
A First Book of ANSI C Fourth Edition
Based on slides created by Bjarne Stroustrup & Tony Gaddis
The Three Attributes of an Identifier
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Chapter 7 - Functions

Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to function’s task(s) u Two groups –Library –Programmer-defined Lesson 7.1

Function Categories u Return no value u Return a single value u Use “pass by reference” Lesson 7.1

Function Basics u Need three things to use function –Function declaration (prototype) t Indicates function exists and describes it t Must be done before use of function –Function call (invocation) t Causes control to transfer from function to function –Function definition t Header line followed by function body enclosed in braces Lesson 7.1

Function Declaration u Indicates function name, return type and types of values passed to function u General form ftype fname (atype, atype); u ftype is function return type u fname is function name u atype is argument type (may be different) –multiple argument separated by commas Lesson 7.1

Function Call u Transfers program control to function u General form fname (exp1, exp2); u fname is function name u exp1 and exp2 are arguments –Variables or constants –Called argument list Lesson 7.1

Function Definition u Includes function’s executable statements u General form (example with two arguments) Lesson 7.1 Function return type Function argument declarations Function body ftype fname (atype aname, atype aname) { … }

Argument Lists u Lists in function call and function header must coordinate –number –order –type u Example: Lesson 7.1 kinetic_energy (mass, velocity); void kinetic_energy (int m, double v) Function call in main Function header 2 arguments in each mass should be declared an integer and velocity a double in program

Function Arrangement u Not necessary for first function to be main u Function definition must be located outside body of any other function u Can write function declaration outside body of all functions or within function –if within, can only be called from function where declared u Function declaration MUST appear before call Lesson 7.1

Function Storage u When function called, memory allocated for –Variables in argument list –Variables declared in function body u When completes execution, memory freed and variable values lost –Can prevent lost and maintain u Called multiple times, allocated and freed repeatedly Lesson 7.1

Common Errors u Argument order not matching between function call and header u Mismatching data types u Pass more information than function needs to complete task Lesson 7.1

Returning a Value u Two items needed –appropriate return type for function –return statement in function u Function declaration and definition list return data type int fact(double); int fact(double arg) u return statement form return expression; Lesson 7.2 Can put expression in ( ).

Return Statement u Considered to be jump statement u Can appear anywhere in function body u More than one return statement can appear in function Lesson 7.2 if (expression) { return (a); } else { return (b); }

Returning Value From main u void type function do not return values –control transfers back to calling function automatically int main ( ) return (0); u Returns value 0 to operating system indicating normal termination Lesson 7.2

Recap: Pass By Value u Default u Function called –Memory set aside and value copied into new memory location –Calculations done inside function using value –When function finished executing, memory location destroyed Lesson 7.2

Pass By Reference u Use argument list to allow function to directly use calling function's values u Reference symbol & required in function declaration and header –Indicate arguments that will have values modified –Create aliases for original variable names Lesson 7.3

Pass By Reference u Example: Lesson 7.3 void func_name (int, double, double&, int&); func_name (x, y, z, a); void func_name ( int b, double c, double& d, int& e) Declaration Call Header x y z a b c d e

Scope u Refers to region in which declaration is active u Three kinds of scope –Block t Variable valid with block of code enclosed in braces –Function t Variable valid only within function where defined –File t Variable valid throughout all modules in file u Determined by identifier's declaration location Lesson 7.4

Scope Lesson 7.4 File containing functions main ( ) and calc ( ) int days; Function calc ( ) int y; for (int n=0;n<8;n++) { } Function main ( ) int x; for (int j=0;j<8;j++) { } days x x y y nj

Storage Classes u Allows manual modification to scope and storage rules u Stated in the declaration u Four specifiers –register : store in register –auto : memory freed after function executes –static : memory persists after function executes –extern : global variables among files Lesson 7.5

static u Variable maintains storage space and value after function finishes executing u Memory reserved and initialized only once –First time function called u General form: static type variable; u Can be initialized in declaration –Done once, does not initialize on other calls Lesson 7.5

Comparing global and static Variables u Similarity –Permanent storage created for both u Difference –Scope t Static variables accessed only from function in which declared t Global variables accessed from any function –With extern from any file Lesson 7.5

extern u Multiple files help manage large programs u Each compiled separately then linked to create executable file u Share variable –Variable declared as global without specifier in one file –Other files extern type variable; Lesson 7.5

Default Arguments u Argument assigned particular value when argument omitted in function call u Values specified in function declaration u Must have ordinary argument listed prior to default arguments Lesson 7.6 type function_name ( ordinary arguments, default arguments);

Using Default Arguments u Calling function –Must be called with at least the number of ordinary arguments void commute (double, double = 15.0, int = 8); commute ( 40.0 ); Call uses 40.0 for first argument, then default values: 15.0 for second argument and 8 for third Cannot specify first and third and use default for second – must have all defaults last! Lesson 7.6

Function Overloading u Defining two or more functions with same name u Each function takes different number of arguments –C++ knows which function is being called by counting number of arguments used –Should not use default arguments since ambiguity could result Lesson 7.7

Generating Random Numbers u Need three functions –rand ( ) t Returns pseudorandom integer in range 0 to –srand ( ) t Operates with rand( ) using global variable invisible to programmer –time ( ) t Returns number of seconds from midnight u Need mod (%) operator to restrict range Lesson 7.8

Generating a Random Number u rand( ) and srand ( ) work together –srand ( ) automatically "seeds" function rand ( ) –Functions linked through global variable u time ( ) used to get true random effect srand (time (0)); rand ( ) returns single integer time of day in seconds Call to create random number Lesson 7.8

Random Number in Specific Range u Use mod operator u Example: n = rand ( ); roll = (n % 6) + 1; Simulate roll of die so result should be integer from 1 to 6 Lesson 7.8

Summary u Define and call functions u Determine the scope of a variable u Pass values by reference u Overload functions u Create random numbers Chapter 7 Learned how to: