CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
Chapter 5: Loops and Files.
Starting Out with C++, 3 rd Edition 1 Chapter 6 Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
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.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
CS102 Introduction to Computer Programming Chapter 6 Functions Part I.
Chapter 6: Functions Starting Out with C++ Early Objects
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
#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.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Starting Out with C++: From Control Structures through Objects
Chapter 7: User-Defined Functions II
Chapter 6 Functions.
Person 1 Translate to Indonesia & presentation Start Next Week
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Addis Ababa Institute of Technology Yared Semu May 2012
Chapter 8 Repetition Statements
6.12 Default Arguments.
Additional Control Structures
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Functions.
6 Chapter Functions.
CS150 Introduction to Computer Science 1
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Fundamental Programming
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

CS102 Introduction to Computer Programming Chapter 6 Functions Continued

2 Chapter 6 Topics Storage Classes Static Local Variables Default Arguments Using Reference Variables as Parameters Inline Functions Overloaded Functions The exit() and atexit() Functions Stubs and drivers Testing Branches and Paths

3 Storage Classes Four types of storage classes Automatic VariablesExternal Variables Register Variables Static Variables All variables are assigned a default class –You can specify a variables storage class by placing the class name before its data type –This will affect the variables lifetime not its scope Concept - All variables belong to a storage class, which determines the period of time the variable exists in memory.

4 Static Variables Used to allow a local variable to remain in existence between function calls –makes the variable exist for the life time of the program –a static variable is only initialized once, when it is created static data_type value; ex. static int Num; Concept - The variables stored in a functions local variables do not persist between function calls

5 Program 6-20 /* This program shows that local variables do not retain their values between function calls. */ #include // Function prototype void ShowLocal(void); void main(void) { ShowLocal(); } /* Definition of function ShowLocal. The initial value of LocalNum, which is 5, is displayed. The value of LocalNum is then changed to 99 before the function returns. */ void ShowLocal(void) { int LocalNum = 5; // Local variable cout << "LocalNum is " << LocalNum << endl; LocalNum = 99; } Program Output LocalNum is 5

6 Program 6-21 /* This program uses a static local variable */ #include // Function prototype void ShowStatic(void); void main(void) { for (int Count = 0; Count < 5; Count++) ShowStatic(); } // Definition of function ShowStatic. void ShowStatic(void) { static int StatNum = 0; cout << "StatNum is " << StatNum << endl; StatNum++; } StatNum is 0 Program Output StatNum is 1 StatNum is 2 StatNum is 3 StatNum is 4 This program demonstrates the effect of defining a variable as static

7 Default Arguments The value of a default argument must be a constant (a literal value or a named constant) When an argument is left out of a function call, all the arguments that come after it must be left out as well. If a function has a mixture of parameters, the parameters with default arguments must be declared last. Concept - Default arguments are passed to parameters automatically if no argument is provided in the function call.

8 Defining Default Arguments In the function prototype void showArea (float = 20, float = 10); void showArea (float length = 20, float width = 10); In the function definition void showArea (float length = 20, float width = 10) float area = length * width; cout << “the area is “ << area << endl: Concept – If there is not function prototype the default arguments can be placed in the function definition

9 Program 6-23 /* This program demonstrates default function arguments. */ #include // Function prototype with default arguments */ void DisplayStars(int = 10, int = 1); void main(void) { DisplayStars(); cout << endl; DisplayStars(5); cout << endl; DisplayStars(7, 3); } /* Definition of function DisplayStars. The default argument for Cols is 10 and for Rows is 1. This function displays a rectangle made of asterisks. */ void DisplayStars(int Cols, int Rows) { /* Nested loop. The outer loop controls the rows and the inner loop controls the columns. */ for (int Down = 0; Down < Rows; Down++) { for (int Across = 0; Across < Cols; Across++) cout << "*"; cout << endl; } Program Output ********** ***** *******

10 Using Reference Variables as Parameters A reference variable is an alias to another variable. Reference variables are declared with an & in front of the variable name data_type &variable_name;ex. int &Num; Reference variables in function prototype statements, include the & after the data type return_type function-name( data_type & ); ex.Void func ( int & ); Concept - Reference variables allow a function to access the parameters original argument and apply changes to it.

11 Program 6-24 /* This program uses a reference variable as a function parameter. */ #include /* Function prototype. The parameter is a reference variable. */ void DoubleNum(int &); void main(void) { int Value = 4; cout << "In main, Value is " << Value << endl; cout << "Now calling DoubleNum..." << endl; DoubleNum(Value); cout << "Now back in main. Value is " << Value << endl; } /* Definition of DoubleNum. The parameter RefVar is a reference variable. The value in RefVar is doubled. */ void DoubleNum (int &RefVar) { RefVar *= 2; } Program Output In main, Value is 4 Now calling DoubleNum... Now back in main. Value is 8 Reference Variable

12 Program 6-25 /* This program uses reference variables as function parameters*/ #include /* Function prototypes. Both functions use reference variables as parameters*/ void DoubleNum(int &); void GetNum(int &); void main(void) { int Value; GetNum(Value); DoubleNum(Value); cout << "That value doubled is " << Value << endl; } /* Definition of GetNum. The parameter UserNum is a reference variable. The user is asked to enter a number, which is stored in UserNum. */ void GetNum(int &UserNum) { cout << "Enter a number: "; cin >> UserNum; } /* Definition of DoubleNum. The parameter RefVar is a reference variable. The value in RefVar is doubled. */ void DoubleNum (int &RefVar) { RefVar *= 2; } Program Output Enter a number: 12 [Enter] That value doubled is 24

13 Reference Argument Warning Don’t get carried away with using reference variables as function parameters. Any time you allow a function to alter a variable that’s outside the function, you are creating potential debugging problems. Reference variables should only be used as parameters when the situation demands them.

14 Overloaded Functions C++ uses both the function name and the parameter list to determine which function is being called. C++ will match the argument list of the function call with the parameter list of the functions defined and find a unique match. Concept - Two or more functions may have the same name as long as their parameter lists are different.

15 Program 6-26 /* This program uses overloaded functions */ #include // Function prototypes int Square(int); float Square(float); void main(void) { int UserInt; float UserFloat; cout.precision(2); cout << "Enter an integer and a floating-point value: "; cin >> UserInt >> UserFloat; cout << "Here are their squares: "; cout << Square(UserInt) << " and " << Square(UserFloat); } */ Definition of overloaded function Square. This function uses an int parameter, Number. It returns the square of Number as an int. */ int Square(int Number) { return Number * Number; } /* Definition of overloaded function Square. This function uses a float parameter, Number. It returns the square of Number as a float.*/ float Square(float Number) { return Number * Number; } Program Output Enter an integer and floating- point value: [Enter] Here are their squares: 144 and 17.64

16 The exit and atexit Functions Must #include stdlib.h to use exit() and atexit function exit returns and integer: ex. exit(0); –this value is returned to the operating system that your program is running within. –EXIT_FAILURE and EXIT_SUCCESS atexit registers a function to be called when the exit function is executed: ex. atexit(stop); Concept - exit and atexit provides a mechanism for terminating a program while executing in a function.

17 Program 6-30 /* This program shows how the exit function causes a program to stop executing.*/ #include #include // For exit void Function(void); // Function prototype void main(void) { Function(); } /* This function simply demonstrates that exit can be used to terminate a program from a function other than main. */ void Function(void) { cout << "This program terminates with the exit function.\n"; cout << "Bye!\n"; exit(0); cout << "This message will never be displayed\n"; cout << "because the program has already terminated.\n"; } Program Output This program terminates with the exit function. Bye!

18 Program 6-31 /* This program demonstrates the exit function. */ #include #include // For exit #include // For toupper void main(void) { char Response; cout << "This program terminates with the exit function.\n"; cout << "Enter S to terminate with the EXIT_SUCCESS code\n"; cout << "or F to terminate with the EXIT_FAILURE code: "; cin >> Response; switch (Response) {case 's' : case 'S' :cout << "Exiting with EXIT_SUCCESS.\n"; exit(EXIT_SUCCESS); case 'f' : case 'F' : cout << "Exiting with EXIT_FAILURE.\n"; exit(EXIT_FAILURE);} } Program Output This program terminates with the exit function. Enter S to terminate with the EXIT_SUCCESS code or F to terminate with the EXIT_FAILURE code: s [Enter] Exiting with EXIT_SUCCESS. Program Output This program terminates with the exit function. Enter S to terminate with the EXIT_SUCCESS code or F to terminate with the EXIT_FAILURE code: f [Enter] Exiting with EXIT_FAILURE.

19 Stubs and Drivers A stub is a dummy function that can be quickly implemented and called in place of the real function A driver is program that tests a function by calling it with a range of test data passed in as arguments. Concept – Stubs and Drivers are very helpful tools for testing and debugging programs that use functions

20 Stubs Functionally decompose your program into individual algorithms and subroutines Write Stubs that allow your top level functions to continue executing –return static or typical values –Display debug messages –Simply return without doing anything Replace the stubs with the real functions when you have completed debugging the top level functions Concept – Stubs allow you to focus on the logical flow of a program with out having to write all the code.

21 Stubs for Menu Calls Switch (choice) { case 1 : Adult (months); break; case 2 : Child (months); break; case 3 : Senior (months); break; case 4 : exit(0); break; default: cout <<"Enter a number"; cout <<" between 1 - 4"; } void Adult (int period) { cout << “You have called the Adult function”; } void Adult (int period) { cout << “You have called the Child function”; } void Adult (int period) { cout << “You have called the Senior function”; }

22 Drivers Develop the function based on the written specification Write a program that calls the function with various arguments as inputs –In range –Out of range –Exercise each path or branch Use the calling program to display the results Concept – Drivers allow you to develop functions independent of the calling functions