Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

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.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
// Functions that take no arguments #include using namespace std; void function1(); void function2( void ); int main() { function1(); function2(); return.
Overview creating your own functions calling your own functions.
Starting Out with C++, 3 rd Edition 1 Chapter 6 Functions.
Computer Science 1620 Programming & Problem Solving.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
1 11/8/06CS150 Introduction to Computer Science 1 More Functions! page 343 November 8, 2006.
Chapter 6: Functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
1 Chapter 9 Scope, Lifetime, and More on Functions.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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
CS102 Introduction to Computer Programming Chapter 6 Functions Continued.
Starting Out with C++: From Control Structures through Objects 7 th edition By Tony Gaddis Source Code Chapter 4.
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.
Lecture 8: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 Chapter 9 Scope, Lifetime, and More on Functions.
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.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Starting Out with C++: From Control Structures through Objects
Chapter 6 Functions.
Person 1 Translate to Indonesia & presentation Start Next Week
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Addis Ababa Institute of Technology Yared Semu May 2012
Chapter 9 Scope, Lifetime, and More on Functions
Functions.
6 Chapter Functions.
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Fundamental Programming
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220

Returning a Boolean value Concept: Functions may return true or false values bool isValid(int number) { bool status; if (number >=1 && number <=100) { status = true; } else { status = false; } return status; } int value = 20; if(isValid(value)) { cout << “The value is within range.\n”; } else { cout << “The value is out of range.\n”; }

// This program uses a function that returns true or false. #include using namespace std; // Function prototype bool isEven(int); int main() { int val; // Get a number from the user. cout << "Enter an integer and I will tell you "; cout << "if it is even or odd: "; cin >> val; // Indicate whether it is even or odd. if (isEven(val)) cout << val << " is even.\n"; else cout << val << " is odd.\n"; return 0; } //***************************************************************** // Definition of function isEven. This function accepts an * // integer argument and tests it to be even or odd. The function * // returns true if the argument is even or false if the argument * // is odd. The return value is an bool. * //***************************************************************** bool isEven(int number) { bool status; if (number % 2 == 0) status = true; // number is even if there is no remainder. else status = false; // Otherwise, the number is odd. return status; }

Local and Global Variables Concept: A local variable is defined inside a function and is not accessible outside the function. A global variable is defined outside all functions and is accessible to all functions in its scope. Local variable lifetime: a function’s local variables only exist while the function is executing Global Variables and Constants: Scope-> from variable definition until the end If not initialized: automatically initialized to zero.

// This program shows that variables defined in a function // are hidden from other functions. #include using namespace std; void anotherFunction(); // Function prototype int main() { int num = 1; // Local variable cout << "In main, num is " << num << endl; anotherFunction(); cout << "Back in main, num is " << num << endl; return 0; } //***************************************************** // Definition of anotherFunction * // It has a local variable, num, whose initial value * // is displayed. * //***************************************************** void anotherFunction() { int num = 20; // Local variable cout << "In anotherFunction, num is " << num << endl; } // This program shows that a global variable is visible // to all the functions that appear in a program after // the variable's declaration. #include using namespace std; void anotherFunction(); // Function prototype int num = 2; // Global variable int main() { cout << "In main, num is " << num << endl; anotherFunction(); cout << "Back in main, num is " << num << endl; return 0; } //***************************************************** // Definition of anotherFunction * // This function changes the value of the * // global variable num. * //***************************************************** void anotherFunction() { cout << "In anotherFunction, num is " << num << endl; num = 50; cout << "But, it is now changed to " << num << endl; }

// This program has an uninitialized global variable. #include using namespace std; int globalNum; // Global variable, automatically set to zero int main() { cout << "globalNum is " << globalNum << endl; return 0; }

Be careful with global variables! Programs may be easier to write, but: Makes debugging difficult Makes functions dependant on code, so later use becomes difficult Makes the program hard to understand Anything you need in a function can be passed. Thus, global variables should really be used for constants

// This program calculates gross pay. #include using namespace std; // Global constants const double PAY_RATE = 22.55; // Hourly pay rate const double BASE_HOURS = 40.0; // Max non-overtime hours const double OT_MULTIPLIER = 1.5; // Overtime multiplier // Function prototypes double getBasePay(double); double getOvertimePay(double); int main() { double hours, // Hours worked basePay, // Base pay overtime = 0.0, // Overtime pay totalPay; // Total pay // Get the number of hours worked. cout << "How many hours did you work? "; cin >> hours; // Get the amount of base pay. basePay = getBasePay(hours); // Get overtime pay, if any. if (hours > BASE_HOURS) overtime = getOvertimePay(hours); // Calculate the total pay. totalPay = basePay + overtime; // Set up numeric output formatting. cout << setprecision(2) << fixed << showpoint; // Display the pay. cout << "Base pay: $" << basePay << endl; cout << "Overtime pay $" << overtime << endl; cout << "Total pay $" << totalPay << endl; return 0; } //************************************************ // The getBasePay function accepts the number of * // hours worked as an argument and returns the * // employee's pay for non-overtime hours. * //************************************************ double getBasePay(double hoursWorked) { double basePay; // To hold base pay // Determine base pay. if (hoursWorked > BASE_HOURS) basePay = BASE_HOURS * PAY_RATE; else basePay = hoursWorked * PAY_RATE; return basePay; } //************************************************* // The getOvertimePay function accepts the number * // of hours worked as an argument and returns the * // employee's overtime pay. * //************************************************* double getOvertimePay(double hoursWorked) { double overtimePay; // To hold overtime pay // Determine overtime pay. if (hoursWorked > BASE_HOURS) { overtimePay = (hoursWorked - BASE_HOURS) * PAY_RATE * OT_MULTIPLIER; } else overtimePay = 0.0; return overtimePay; }

Same Name // This program demonstrates how a local variable // can shadow the name of a global constant. #include using namespace std; // Gobal constant. const int BIRDS = 500; // Function prototype void california(); int main() { cout << "In main there are " << BIRDS << " birds.\n"; california(); return 0; } //******************************************** // california function * //******************************************** void california() { const int BIRDS = 10000; cout << "In california there are " << BIRDS << " birds.\n"; }

Static Local Variables If a function is called more than once in a program, the values stored in the function’s local variables do not persist between function calls Remedy: static Static variables are not destroyed when a function returns, they exist for the lifetime of the program, even though their scope is only the function in which the are defined

// This program shows that local variables do not retain // their values between function calls. #include using namespace std; // Function prototype void showLocal(); int main() { showLocal(); return 0; } //*********************************************************** // 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() { int localNum = 5; // Local variable cout << "localNum is " << localNum << endl; localNum = 99; } // This program uses a static local variable. #include using namespace std; void showStatic(); // Function prototype int main() { // Call the showStatic function five times. for (int count = 0; count < 5; count++) showStatic(); return 0; } //************************************************************** // Definition of function showStatic. * // statNum is a static local variable. Its value is displayed * // and then incremented just before the function returns. * //************************************************************** void showStatic() { static int statNum; cout << "statNum is " << statNum << endl; statNum++; }

// This program shows that a static local variable is only // initialized once. #include using namespace std; void showStatic(); // Function prototype int main() { // Call the showStatic function five times. for (int count = 0; count < 5; count++) showStatic(); return 0; } //************************************************************** // Definition of function showStatic. * // statNum is a static local variable. Its value is displayed * // and then incremented just before the function returns. * //************************************************************** void showStatic() { static int statNum = 5; cout << "statNum is " << statNum << endl; statNum++; }

Default arguments Concept: Default arguments are passed to parameters automatically if no argument is provided in the function call. void showArea(double = 20.0, double = 10.0); void showArea(double length = 20.0, double width = 10.0); showArea();

// This program demonstrates default function arguments. #include using namespace std; // Function prototype with default arguments void displayStars(int = 10, int = 1); int main() { displayStars(); // Use default values for cols and rows. cout << endl; displayStars(5); // Use default value for rows. cout << endl; displayStars(7, 3); // Use 7 for cols and 3 for rows. return 0; } //******************************************************** // Definition of function displayStars. * // The default argument for cols is 10 and for rows is 1.* // This function displays a square 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; }

Using Reference Variables as Parameters (Pass by reference) Concept: When used as parameters, reference variables allow a function to access the parameter’s original argument. Changes to the parameter are also made to the argument. void doubleNum(int &refVar) { refVar *= 2; } void doubleNum(int &);

// This program uses a reference variable as a function // parameter. #include using namespace std; // Function prototype. The parameter is a reference variable. void doubleNum(int &); int main() { 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; return 0; } //********************************************************** // Definition of doubleNum. * // The parameter refVar is a reference variable. The value * // in refVar is doubled. * //********************************************************** void doubleNum (int &refVar) { refVar *= 2; } // This program uses reference variables as function parameters. #include using namespace std; // Function prototypes. Both functions use reference variables // as parameters. void doubleNum(int &); void getNum(int &); int main() { int value; // Get a number and store it in value. getNum(value); // Double the number stored in value. doubleNum(value); // Display the resulting number. cout << "That value doubled is " << value << endl; return 0; } //************************************ ************************* // 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; }

Overloading Functions Concept: Two or more functions may have the same name, as long as their parameter lists are different C++ uses this difference to figure out which function to use This is called a functions’ signature int square(int number) double square(double number)

// This program uses overloaded functions. #include using namespace std; // Function prototypes int square(int); double square(double); int main() { int userInt; double userFloat; // Get an int and a double. cout << fixed << showpoint << setprecision(2); cout << "Enter an integer and a floating-point value: "; cin >> userInt >> userFloat; // Display their squares. cout << "Here are their squares: "; cout << square(userInt) << " and " << square(userFloat); return 0; } //************************************************************** // 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 double parameter, number. It returns * // the square of number as a double. * //*************************************************************** double square(double number) { return number * number; }

// This program demonstrates overloaded functions to calculate // the gross weekly pay of hourly-paid or salaried employees. #include using namespace std; // Function prototypes void getChoice(char &); double calcWeeklyPay(int, double); double calcWeeklyPay(double); int main() { char selection; // Menu selection int worked; // Hours worked double rate; // Hourly pay rate double yearly; // Yearly salary // Set numeric output formatting. cout << fixed << showpoint << setprecision(2); // Display the menu and get a selection. cout << "Do you want to calculate the weekly pay of\n"; cout << "(H) an hourly-paid employee, or \n"; cout << "(S) a salaried employee?\n"; getChoice(selection); // Process the menu selection. switch (selection) { // Hourly-paid employee case 'H' : case 'h' : cout << "How many hours were worked? "; cin >> worked; cout << "What is the hour pay rate? "; cin >> rate; cout << "The gross weekly pay is $"; cout << calcWeeklyPay(worked, rate) << endl; break; // Salaried employee case 'S' : case 's' : cout << "What is the annual salary? "; cin >> yearly; cout << "The gross weekly pay is $"; cout << calcWeeklyPay(yearly) << endl; break; } return 0; } //************************************************************* // Definition of function getChoice. * // The parameter letter is a reference to a char. * // This function asks the user for an H or an S and returns * // the validated input. * //************************************************************* void getChoice(char &letter) { // Get the user's selection. cout << "Enter your choice (H or S): "; cin >> letter; // Validate the selection. while (letter != 'H' && letter != 'h' && letter != 'S' && letter != 's') { cout << "Please enter H or S: "; cin >> letter; } //*********************************************************** // Definition of overloaded function calcWeeklyPay. * // This function calculates the gross weekly pay of * // an hourly-paid employee. The parameter hours holds the * // number of hours worked. The parameter payRate holds the * // hourly pay rate. The function returns the weekly salary. * //*********************************************************** double calcWeeklyPay(int hours, double payRate) { return hours * payRate; } //*********************************************************** // Definition of overloaded function calcWeeklyPay. * // This function calculates the gross weekly pay of * // a salaried employee. The parameter holds the employee's * // annual salary. The function returns the weekly salary. * //*********************************************************** double calcWeeklyPay(double annSalary) { return annSalary / 52; }

The exit() function Concept: The exit() function causes a program to terminate, regardless of which function or control mechanism is executing. // This program shows how the exit function causes a program // to stop executing. #include #include // For exit using namespace std; void function(); // Function prototype int main() { function(); return 0; } //******************************************* **************** // This function simply demonstrates that exit can be used * // to terminate a program from a function other than main. * //******************************************* **************** void function() { 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"; }

Stubs and Drivers Stub: a dummy function that is called instead of the actual function it represents Used to determine if the program calling the function is working correctly When your done with this part, move on to developing the actual function Driver: a program that tests a function simply by calling it

// This program is a driver for testing the showFees function. #include using namespace std; // Prototype void showFees(double, int); int main() { // Constants for membership rates const double ADULT = 40.0; const double SENIOR = 30.0; const double CHILD = 20.0; // Perform a test for adult membership. cout << "Testing an adult membership...\n" << "Calling the showFees function with arguments " << ADULT << " and 10.\n"; showFees(ADULT, 10); // Perform a test for senior citizen membership. cout << "\nTesting a senior citizen membership...\n" << "Calling the showFees function with arguments " << SENIOR << " and 10.\n"; showFees(SENIOR, 10); // Perform a test for child membership. cout << "\nTesting a child membership...\n" << "\nCalling the showFees function with arguments " << CHILD << " and 10.\n"; showFees(CHILD, 10); return 0; } //***************************************************************** // Definition of function showFees. The memberRate parameter * // the monthly membership rate and the months parameter holds the * // number of months. The function displays the total charges. * //***************************************************************** void showFees(double memberRate, int months) { cout << "The total charges are $" << (memberRate * months) << endl; }