C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.

Slides:



Advertisements
Similar presentations
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
Advertisements

Chapter 5 Functions.
Computer Science 1620 Loops.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Computer Science 1620 Programming & Problem Solving.
Chapter 6: User-Defined Functions I
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Object-Oriented Programming Using C++ CLASS 27.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
CSC 221: Computer Programming I Fall 2001  top-down design  approach to problem solving, program design  focus on tasks, subtasks, …  reference parameters.
GE 211 King Saud university Dr. Ahmed Telba. #include using namespace std; int main() { int i, j; double x, y; cout
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Fundamental Programming: Fundamental Programming Introduction to C++
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
1 CSE 2341 Object Oriented Programming with C++ Note Set #5.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions. Predefined Functions C++ comes with libraries of code that can be reused in your programs. The code comes in the form of predefined functions.
Programming Fundamentals Enumerations and Functions.
1 Object-Oriented Programming Using C++ CLASS 2 Honors.
1 Class 19 Chapter 13 – Creating a class definition.
Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
What Is? function predefined, programmer-defined
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 1.2 Introduction to C++ Programming
Predefined Functions Revisited
FUNCTIONS IN C++.
Chapter 4: Subprograms Functions for Problem Solving
Value returning Functions
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 Pass By Value Pass by Reference
Chapter 6: User-Defined Functions I
Fundamental Programming
Separate Compilation.
Predefined Functions Revisited
What Is? function predefined, programmer-defined
Presentation transcript:

C++ Functions

Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2

Objective 1: Implementing C++ functions What is a function? What is a function? Understand two difference function types and their structures. Understand two difference function types and their structures. How to implement each function? How to implement each function? 3

Structure of Essay 4 Version 1 Version 2 One point for each paragraph divide and conquer

Divide & Conquer in Software Development We implement app to finish a task. We implement app to finish a task. The task is divided into smaller tasks The task is divided into smaller tasks Implementing each simple task by a function Implementing each simple task by a function 5 divide processingIncomeTaxesgetIncomecomputeTaxesprintTaxes conquer

Paragraph vs Function Consists of one or more sentences, Consists of one or more sentences, Deals with one point Deals with one point Begins on a new usually indented line Begins on a new usually indented line Consists of one or more statements Consists of one or more statements Deals with one smaller task Deals with one smaller task Begins with a function name Begins with a function name 6

Function Types Standard Standard User-defined User-defined 7

8 Standard Functions Build-in functions Build-in functions Organized in 100+libraries Organized in 100+libraries How to use a build-in function? How to use a build-in function? Where are libraries Where are libraries Which function you want to use Which function you want to use Does the function need inputs Does the function need inputs

9 Standard Math Functions #include #include using namespace std; int main() { // Getting a double value double x; cout << "Please enter a real number: "; cin >> x; // Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl; }

Demo Using online IDE Using online IDE ceil(2.5) =3 ceil(2.5) =3 floor(2.5)=2 floor(2.5)=2 10

Hands-on Experience (1) ceil(-2.5) =? ceil(-2.5) =? floor(-2.5)=? floor(-2.5)=? Hint Hint Copy and paste code to using new input (-2.5) Copy and paste code to using new input (-2.5) 11

12 Standard Character Functions #include // input/output handling #include // character type functions using namespace std; int main() { char ch; cout << "Enter a character: "; cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl; cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl; if (isdigit(ch)) cout << "'" << ch <<"' is a digit!\n"; else cout << "'" << ch <<"' is NOT a digit!\n"; } Explicit casting vs cctype

Demo At least two test cases are required At least two test cases are required Char is an alphabet (x) Char is an alphabet (x) Char is a digit (5) Char is a digit (5) 13

14 User-Defined Functions Implement a function Implement a function to determine if a triangle is to determine if a triangle is library does not include a standard function library does not include a standard function

15 Define a Function? Step #1 – Implement the function in.cpp Step #1 – Implement the function in.cpp Step #2 – publish the function in Step #2 – publish the function in before the main function of the program before the main function of the program for yourself for yourself a header file (.h file) a header file (.h file) for you or other people reuse for you or other people reuse Step #3 (if using header) – Use the functions in main.cpp Step #3 (if using header) – Use the functions in main.cpp

16 Syntactic Structure of a Function? The function header The function header ( ) ( ) The function body enclosed between The function body enclosed between { }

17 Example of User-defined Function double computeTax(double income) { if (income < ) return 0.0; if (income < ) return 0.0; double taxes = 0.07 * (income ); double taxes = 0.07 * (income ); return taxes; return taxes;}

18 double computeTax(double income) { if (income < ) return 0.0; if (income < ) return 0.0; double taxes = 0.07 * (income ); double taxes = 0.07 * (income ); return taxes; return taxes;} Example of User-defined Function Function header Descriptive name

19 Example of User-defined Function double computeTax(double income) { if (income < ) return 0.0; if (income < ) return 0.0; double taxes = 0.07 * (income ); double taxes = 0.07 * (income ); return taxes; return taxes;} Function header Function body

How to Improvement double computeTax(double income) { if (income < ) return 0.0; if (income < ) return 0.0; double taxes = 0.07 * (income ); double taxes = 0.07 * (income ); return taxes; return taxes;} 20 double computeTax(double income) { const double baseIncome=5000.0; const double baseIncome=5000.0; const double taxRates=0.07; const double taxRates=0.07; double taxes =-1.0; double taxes =-1.0; if (income < baseIncome) { if (income < baseIncome) { taxes=0.0; taxes=0.0; } else { } else { taxes = taxRates * (income-baseIncome); taxes = taxRates * (income-baseIncome); } return taxes; return taxes;} Original version Improved version refactoring

How to Improvement 21 double computeTax(double income, double baseIncome, double taxRates) { double baseIncome, double taxRates) { const double baseIncome=5000.0; const double baseIncome=5000.0; const double taxRates=0.07; const double taxRates=0.07; double taxes =-1.0; double taxes =-1.0; if (income < baseIncome) { if (income < baseIncome) { taxes=0.0; taxes=0.0; } else { } else { taxes = taxRates * (income-baseIncome); taxes = taxRates * (income-baseIncome); } return taxes; return taxes;} Improved version 2 refactoring double computeTax(double income) { const double baseIncome=5000.0; const double baseIncome=5000.0; const double taxRates=0.07; const double taxRates=0.07; double taxes =-1.0; double taxes =-1.0; if (income < baseIncome) { if (income < baseIncome) { taxes=0.0; taxes=0.0; } else { } else { taxes = taxRates * taxes = taxRates * (income-baseIncome); (income-baseIncome); } return taxes; return taxes;} Improved version

22 Function Header vs. Signature Example Example double computeTaxes(double) ; Unnamed Parameter Semicolon ;

23 TaxesMain.cpp #include #include using namespace std; // Function Signature double getIncome(string); double getIncome(string); double computeTaxes(double); double computeTaxes(double); void printTaxes(double); void printTaxes(double); int main() { // Get the income; double income = getIncome("Please enter the employee income: "); // Compute Taxes double taxes = computeTaxes(income); // Print employee taxes printTaxes(taxes);} double computeTaxes(double income) { if (income<5000) return 0.0; if (income<5000) return 0.0; return 0.07*(income ); return 0.07*(income );} double getIncome(string prompt) { cout << prompt; cout << prompt; double income; double income; cin >> income; cin >> income; return income; return income;} void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; cout << "The taxes is $" << taxes << endl;}

1. Copy and paste code 2. Add signatures 3. Replacing the red statements with refactored code 4. Test your code Solution: 3Iwf Solution: 3Iwf 24 #include #include using namespace std; // Function Signature // add signature here // add signature here int main() { // Get the income; double income = getIncome("Please enter the employee income: "); // Compute Taxes double taxes = computeTaxes(income); // Print employee taxes printTaxes(taxes);} double computeTaxes(double income) { if (income<5000) return 0.0; if (income<5000) return 0.0; return 0.07*(income ); return 0.07*(income );} double getIncome(string prompt) { cout << prompt; cout << prompt; double income; double income; cin >> income; cin >> income; return income; return income;} void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; cout << "The taxes is $" << taxes << endl;} Hands-on Experience (2)

25 Publish Your Functions Build libraries to be used by you and your customers Build libraries to be used by you and your customers Create header files to store function signatures Create header files to store function signatures

26 // This is a header file structure #ifndef TAXESRULES_H_ // check if a unique value _ #define TAXESRULES_H_ TaxesRules.h compiler directive #include other header files #endif //All functions signatures here _H_ //Never put functions implementation here

27 TAXESRULES_H_ #ifndef TAXESRULES_H_ TAXESRULES_H_ #define TAXESRULES_H_ TaxesRules.h #include using namespace std; /** purpose -- to get the employee income purpose -- to get the employee income input -- a string prompt to be displayed to the user input -- a string prompt to be displayed to the user output -- a double value representing the income output -- a double value representing the income*/ double getIncome(string); // purpose -- to compute the taxes for a given income // input -- a double value representing the income // output -- a double value representing the taxes double computeTaxes(double); void printTaxes(double); #endif

28 TaxesRules.cpp #include “TaxesRules.h" double computeTaxes(double income) { // need to refactor later // need to refactor later if (income<5000) return 0.0; if (income<5000) return 0.0; return 0.07*(income ); return 0.07*(income );} double getIncome(string prompt) { cout << prompt; cout << prompt; double income; double income; cin >> income; cin >> income; return income; return income;} void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; cout << "The taxes is $" << taxes << endl;}

Main Program File 29 TaxesMain.cpp #include “TaxesRules.h" int main() { // Get the income; // Get the income; double income = getIncome("Please enter the employee income: "); double income = getIncome("Please enter the employee income: "); // Compute Taxes // Compute Taxes double taxes = computeTaxes(income); double taxes = computeTaxes(income); // Print employee taxes // Print employee taxes printTaxes(taxes); printTaxes(taxes);}

Files Needed for User-defined Functions Head files Head files TaxesRules.h TaxesRules.h Implementation of the header files Implementation of the header files TaxesRules.cpp TaxesRules.cpp One driver/Main file One driver/Main file TaxesMain.cpp TaxesMain.cpp 30

31 Discussion: Why Do We Need Function Signature? For Information Hiding For Information Hiding Only publish function signatures in a header (.h) file Only publish function signatures in a header (.h) file Hide implementation details Hide implementation details For Function Abstraction For Function Abstraction We can change the implementation details from time to time to We can change the implementation details from time to time to Improve function performance Improve function performance make the customers focus on the purpose of the function, not its implementation make the customers focus on the purpose of the function, not its implementation

Objective 2: Sharing data among functions Global Variable (bad practice) Global Variable (bad practice) Passing parameters Passing parameters Value parameters Value parameters Reference parameters Reference parameters 32

Sharing Using Global Variables 33 Global var

Using Global Variables 34 x 0

Using Global Variables 35 x 0 int main() { f2(); f2(); cout << x << endl ; cout << x << endl ;} 1

Using Global Variables 36 x 0 void main() { f2(); f2(); cout << x << endl ; cout << x << endl ;} 1 void f2() { x += 4; x += 4; f1(); f1();} 2 4

Using Global Variables x void main() { f2(); f2(); cout << x << endl ; cout << x << endl ;} 1 void f2() { x += 4; x += 4; f1(); f1();} 3 void f1() { x++; x++;} 4

Using Global Variables x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 1 void f2() { x += 4; x += 4; f1(); f1();} 3 void f1() { x++; x++;} 5

Using Global Variables x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 1 void f2() { x += 4; x += 4; f1(); f1();} 6

Using Global Variables x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 7

Using Global Variables x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 8

Using Global Variables 42

43 What is Bad About Using Global Vairables? Not safe! Not safe! If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value! If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value! Against The Principle of Information Hiding! Against The Principle of Information Hiding! this gives all functions the freedom to change the values stored in the global variables at any time this gives all functions the freedom to change the values stored in the global variables at any time

Example of Defining and Using Global and Local Variables 44

45 Example of Defining and Using Global and Local Variables x 0 Global variables are automatically initialized to 0

46 Example of Defining and Using Global and Local Variables x 0 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 1

Example of Defining and Using Global and Local Variables 47 x 4 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x ???? 3

Example of Defining and Using Global and Local Variables 48 x 4 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x 10 3

Example of Defining and Using Global and Local Variables 49 x 4 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x 10 4

Example of Defining and Using Global and Local Variables 50 x 4 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x 10 5

Example of Defining and Using Global and Local Variables 51 x 4 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 6

Example of Defining and Using Global and Local Variables 52 x 4 int main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 7

53 Passing Value Parameters Copy the values of the function call’s arguments to callee’s Copy the values of the function call’s arguments to callee’s Any changes in the callee’s value parameters don’t affect the original function arguments Any changes in the callee’s value parameters don’t affect the original function arguments

Example of Using Value Parameters 54 x 0 int main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 1

Example of Using Value Parameters and Global Variables 55 x 4 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 2 void fun(int x ) { cout << x << endl; cout << x << endl; x=x+5; x=x+5;} 3 3

Example of Using Value Parameters 56 x 4 Int main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 2 void fun(int x ) { cout << x << endl; cout << x << endl; x=x+5; x=x+5;} 3 4 8

Example of Using Value Parameters 57 x 4 int main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 2 void fun(int x ) { cout << x << endl; cout << x << endl; x=x+5; x=x+5;} 8 5

Example of Using Value Parameters 58 x 4 int main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 6

Example of Using Value Parameters 59 x 4 int main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 7

60 Passing Reference Parameters Want to change the values of the original function arguments Want to change the values of the original function arguments double update (double & x); FFFF & ampersand

Example of Reference Parameters 61 int main() { int x = 4; int x = 4; fun(x); fun(x); cout << x << endl; cout << x << endl;} 1 x ? x 4

Example of Reference Parameters 62 int main() { int x = 4; int x = 4; fun(x); fun(x); cout << x << endl; cout << x << endl;} 2 x ? x 4 void fun( int & y ) { cout<<y<<endl; cout<<y<<endl; y=y+5; y=y+5;} 3

Example of Reference Parameters 63 int main() { int x = 4; int x = 4; fun(x); fun(x); cout << x << endl; cout << x << endl;} 2 x ? x 4 void fun( int & y ) { cout<<y<<endl; cout<<y<<endl; y=y+5; y=y+5;} 4 9

Example of Reference Parameters 64 int main() { int x = 4; int x = 4; fun(x); fun(x); cout << x << endl; cout << x << endl;} 2 x ? x 9 void fun( int & y ) { cout<<y<<endl; cout<<y<<endl; y=y+5; y=y+5;} 5

Example of Reference Parameters 65 int main() { int x = 4; int x = 4; fun(x); fun(x); cout << x << endl; cout << x << endl;} 6 x ? x 9

Example of Reference Parameters 66 int main() { int x = 4; int x = 4; fun(x); fun(x); cout << x << endl; cout << x << endl;} x ? x 9 7

Hands-on Experience (3) 67

Summary Declare and Implementing C++ functions for reusing Declare and Implementing C++ functions for reusing Passing by value Passing by value Passing by reference Passing by reference 68

69 Function Overloading defined more than once defined more than once different data types or different number of parameters different data types or different number of parameters

Hands-on Experience (4) Add statement Add statement max(3.5, 2) max(3.5, 2) How to fix it? How to fix it? Modify the code at Modify the code at 70