Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Functions  Programmer-Defined Functions  Local Variables in Functions  Overloading Function Names  void Functions,  Call-By-Reference Parameters in.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
Chapter 3 Function Basics Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 ACS 168 Structured Programming Using the Computer Chapter 4 by Joaquin Vila Prepared by Shirley White.
CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
Chapter 6: User-Defined Functions I
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
Copyrights ©2005 Pearson Addison-Wesley. All rights reserved. 1 Chapter 4 Procedural Abstraction and Functions That Return a Value.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
Chapter 6: User-Defined Functions I
CSC 200 Lecture 04 2/8/06 Matt Kayala. Learning Objectives  Predefined Functions  Those that return a value and those that don’t  Programmer-defined.
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 Programming in C++ Computer Science Dept Va Tech August 2000 ©2000 William D McQuain 1 #include // for file streams for input/output #include.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
1 Lecture 3 Part 1 Functions with math and randomness.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Functions for All Subtasks.
Chapter 5 Functions for All Subtasks. Slide 5- 2 Overview 5.1 void Functions 5.2 Call-By-Reference Parameters 5.3 Using Procedural Abstraction 5.4 Testing.
Copyright © 2015 Pearson Education, Ltd.. All rights reserved. Chapter 5 Functions for All Subtasks.
Chapter 3 Procedural Abstraction and Functions That Return a Value.
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Procedural Abstraction and Functions That Return a Value.
1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is.
Slide 1 Chapter 3 Function Basics. Slide 2 Learning Objectives  Predefined Functions  Those that return a value and those that don’t  Programmer-defined.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Top-Down Design SLO1.8 Explain the benefits of dividing large programming tasks to smaller.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Functions for All Subtasks SLO1.8 Explain the benefits of dividing large programming tasks.
Control Structures (B) Topics to cover here: Sequencing in C++ language.
Exposure C++ Chapter VIII Program Modularity and Functions.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
1 MODULAR DESIGN AND ABSTRACTION. 2 SPECIFYING THE DETAILS OF A PROBLEM INTO A RELATED SET OF SMALLER PROBLEMS.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
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.
Chapter 3 : Top Down Design with Functions By Suraya Alias.
Recap……Last Time [Variables, Data Types and Constants]
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
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.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 4 Functions.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
Chapter 6: User-Defined Functions I
Functions for All Subtasks
Chapter 5 Functions for All Subtasks 1
Chapter 5 Functions for All Subtasks 1
Predefined Functions Revisited
Chapter 4 Procedural Abstraction and Functions That Return a Value 1
CMPT 201 Functions.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Functions for All Subtasks
CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Chapter 3 Input output.
Chapter 6: User-Defined Functions I
Predefined Functions Revisited
Chapter 4 Procedural Abstraction and Functions That Return a Value 1
Presentation transcript:

Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4

Top-Down Design First step to designing a program is to understand the problem – Analysis Phase An employee is paid at a rate of $16.78 per hour for regular hours worked in a week. From the worker’s gross pay, 6% is withheld for social security tax, 14% is withheld for federal income tax, 5% is withheld for state income tax, and $10 per week is withheld for union dues. An employee is paid at a rate of $16.78 per hour for regular hours worked in a week. From the worker’s gross pay, 6% is withheld for social security tax, 14% is withheld for federal income tax, 5% is withheld for state income tax, and $10 per week is withheld for union dues.

Top-Down Design If the worker has three or more dependents, then an additional $35 is withheld to cover the extra cost of health insurance beyond what the employer pays. Write a program that will read in the number of hours worked in a week and the number of dependents as input, and will then output the worker’s gross pay, each withholding amount, and the net take-home pay for the week.

Top-Down Design Problem Definition (Analysis) Given an employee’s hourly rate of pay at $16.78, calculate that employee’s net pay. From the worker’s gross pay withhold: Given an employee’s hourly rate of pay at $16.78, calculate that employee’s net pay. From the worker’s gross pay withhold: social security tax = 6% social security tax = 6% federal income tax = 14% federal income tax = 14% state income tax = 5% state income tax = 5% union dues = $10 per week union dues = $10 per week health insurance = $35 if 3 or more dependents health insurance = $35 if 3 or more dependents Input: The number of hours worked in a week Input: The number of hours worked in a week The number of dependents The number of dependents Output: The employee’s gross pay, deduction amounts, and net pay Output: The employee’s gross pay, deduction amounts, and net pay

Top-Down Design PROGRAM DESIGN Initial Algorithm: Initial Algorithm: 1. Read in the hours worked in a week and the number of dependents. 1. Read in the hours worked in a week and the number of dependents. 2. Compute the total gross pay. 2. Compute the total gross pay. 3. Compute the individual deduction amounts. 3. Compute the individual deduction amounts. 4. Compute the net pay. 4. Compute the net pay. 5. Display the results formatted in dollars and cents. 5. Display the results formatted in dollars and cents.

Top-Down Design First step to designing a program is to understand the problem – Analysis Phase Second step, the algorithm is written – Design Phase

PROGRAM DESIGN 1. Read in the hours worked in a week and the number of dependents. 1. Read in the hours worked in a week and the number of dependents. Refine step 1: Refine step 1: cout “; cout “; cin >> hours_worked; cin >> hours_worked; cout << endl; cout << endl; cout “; cout “; cin >> dependents; cin >> dependents; cout << endl; cout << endl;

PROGRAM DESIGN 2. Compute the total gross pay. 2. Compute the total gross pay. Refine step 2: Refine step 2: gross_pay = hours_worked * PAY_RATE gross_pay = hours_worked * PAY_RATE

PROGRAM DESIGN 3. Compute the individual deduction amounts. 3. Compute the individual deduction amounts. Refine step 3: Refine step 3: social_security_tax = gross_pay * SST_RATE social_security_tax = gross_pay * SST_RATE federal_income_tax = gross_pay * FEDERAL_INCOME_RATE federal_income_tax = gross_pay * FEDERAL_INCOME_RATE state_income_tax = gross_pay * STATE_INCOME_RATE state_income_tax = gross_pay * STATE_INCOME_RATE

PROGRAM DESIGN 4. Compute the net pay. 4. Compute the net pay. Refine step 4: Refine step 4: net_pay = gross_pay - (social_security_tax + net_pay = gross_pay - (social_security_tax + federal_income_tax + state_income_tax + federal_income_tax + state_income_tax + UNION_DUES); UNION_DUES); if (dependents => 3) if (dependents => 3) net_pay = net_pay - HEALTH_INSURANCE; net_pay = net_pay - HEALTH_INSURANCE;

PROGRAM DESIGN 5. Display the results formatted in dollars and cents. 5. Display the results formatted in dollars and cents. Refine step 5: Refine step 5: cout << fixed << showpoint << setprecision(2); cout << fixed << showpoint << setprecision(2); cout << “The employee summary of weekly pay is as follows: “; cout << “The employee summary of weekly pay is as follows: “; cout << “Hours worked: “ <<setw(10)<<hours_worked << endl; cout << “Hours worked: “ <<setw(10)<<hours_worked << endl; cout << “Gross pay: “ <<setw(10)<<gross_pay << endl; cout << “Gross pay: “ <<setw(10)<<gross_pay << endl; cout << “Social Security: “<< setw(10) cout << “Social Security: “<< setw(10) << social_security_tax << endl; << social_security_tax << endl; ….. …..

Top-Down Design Implementation –Create interface file (pay.h) –Create implementation file (pay.cpp) –Create application file (main.cpp)

Top-Down Design First step to designing a program is to understand the problem – Analysis Phase Second step, the algorithm is written – Design Phase Third step, code the solution - Implementation Phase Process is called Top-Down Design

Top-Down Design Using this top-down structure in a program makes it easier to write, test, debug, and change in the future C++ calls subtasks functions Using functions allows the work associated with large projects to be divided between team members

Predefined Functions C++ comes with libraries of predefined functions –See Appendix C, pg. 717 for a list of selected C++ Library Facilities

Predefined Functions double the_root; double the_root; the_root = sqrt(9.0); the_root = sqrt(9.0); sqrt is the function name sqrt(9.0) is the function call 9.0 is the argument enclosed in parentheses the value returned by sqrt is of type double

Predefined Functions The argument in a function can be: –a constant –a variable –complicated expression You may use a function call wherever it is legal to use an expression of the type specified for the value returned by the function

Predefined Functions Compiler directives –#include –#include –provides the compiler with information about the library –if your program uses a predefined function, then is must contain a directive naming the header file

Predefined Functions Prototype int = rand ( ); int = rand ( ); What does the prototype tell us about the function? What does the prototype tell us about the function?

Predefined Functions Random Numbers: C++ uses rand( ) to generate random numbers. y = rand( ); y = rand( ); cout << rand( ) << endl; cout << rand( ) << endl; In order to randomize the results of rand( ), the srand( ) function must be used. int seed; int seed; cout “; cout “; cin >> seed; cin >> seed; srand(seed); srand(seed); cout << rand( ) << endl; cout << rand( ) << endl;

Predefined Functions To limit the range of the random number, use the following formula: y = 1 + rand( ) % 100 y = 1 + rand( ) % 100 Where 100 represents the upper limit and 1 is the lower limit to the numbers which could be randomly generated

Predefined Functions int main( ) int main( ) Is the Root Function

Programmer-Defined Functions Two parts to programmer-defined functions: –Function Prototype placed in the header/interface file –Function Definition placed in the implementation file

Programmer-Defined Functions Function Prototype –Describes how the function is called: Name of function Number of arguments used by the function What type the arguments should be What type of value returned by the function Pre- and Postcondition comments that explain the function

Programmer-Defined Functions Prototype: Prototype: double total_cost(int number, double price); double total_cost(int number, double price); // Precondition: the value of number and price is // Precondition: the value of number and price is // available. // available. // Postcondition: the total cost including sales tax // Postcondition: the total cost including sales tax // is returned from the function. // is returned from the function. What is the name of the function? What is the name of the function? How many arguments are defined? How many arguments are defined? What type are the arguments? What type are the arguments? What type is the value returned by the function? What type is the value returned by the function?

Programmer-Defined Functions Arguments of a function prototype are called formal parameters –Considered to be placeholders –Names follow rules for any identifier/variable –Process of substituting values for the formal parameters is known as call-by-value parameters

Programmer-Defined Functions Function call: customer_bill = total_cost(number, price); customer_bill = total_cost(number, price); –right-hand side of equal sign –What is the function name? –What are the arguments?

Programmer-Defined Functions Function Definition –Describes how the function computes its return value –Works like a small program –Header –Body

Programmer-Defined Functions double total_cost(int number, double price) double total_cost(int number, double price) { const double TAX_RATE = 0.06; // 6% sales tax const double TAX_RATE = 0.06; // 6% sales tax double subtotal; double subtotal; subtotal = price * number; subtotal = price * number; return (subtotal + (subtotal * TAX_RATE)); return (subtotal + (subtotal * TAX_RATE)); }

Programmer-Defined Functions Return-statement –keyword return –an expression –the value which will be returned by the function –once the return-statement is executed, the function call ends

Void Functions In C++ a function must: –return a single value or –return no value A function that returns no value is called a void-function

Void Functions Two differences between a function which returns a value and a void function: –keyword void in place of the return type –return-statement does not contain a value to be returned

Void Function Prototype void show_results(double f_degrees, double c_degrees); void show_results(double f_degrees, double c_degrees); //Precondition: the values of f_degrees and c_degrees //Precondition: the values of f_degrees and c_degrees //are available to the function //are available to the function //Postcondition: displays a message that c_degrees //Postcondition: displays a message that c_degrees //Celsius is equivalent to f_degrees Fahrenheit. //Celsius is equivalent to f_degrees Fahrenheit.

Void Function Definition void show_results(double f_degrees, double c_degrees) void show_results(double f_degrees, double c_degrees) { cout << fixed << showpoint << setprecision(1); cout << fixed << showpoint << setprecision(1); cout << f_degrees cout << f_degrees << “ degrees Fahrenheit is equivalent to \n” << “ degrees Fahrenheit is equivalent to \n” << c_degrees << “ degrees Celsius.\n”; << c_degrees << “ degrees Celsius.\n”; return; return; }

C++ Functions Can be any C++ type such as int, char, float, void, etc. Described as “black box” - device you are able to use, but don’t know how it works

C++ Functions Black Box –Method of operation is hidden from the user –User need not know the details of how task is carried out –User needs only to know what function does –Known as procedural abstraction or information hiding –Test each black box as a separate unit!

Local Variables Variables which are declared within a function are called local variables May declare variable in main.cpp program and declare variable within a function which have the same name –compiler sees them as separate variables

Local Variables Variables declared with main.cpp program –local to the main program Call-by-Value Formal Parameters –local to the function Variables declared within a function –local to that function

Pre/Postcondition.

Precondition and Postcondition Should be the first step, prior to writing a function; considered an important part of design Placed immediately after a function prototype Written as a comment

Precondition Provides information about the state of the input argument(s) Appears after function prototype Tells what is assumed to be true before the function is executed

Postcondition Tells what the function does Tells what will be true after execution of the function Describes the state of the variables after execution of the function For functions that return a value, it describes the return value

Examples void get_name_input( ); void get_name_input( ); // Precondition: A name is needed // Precondition: A name is needed // Postcondition: The user is prompted to enter a name. The // Postcondition: The user is prompted to enter a name. The // values are read and stored in the variables first_name and // values are read and stored in the variables first_name and // last_name // last_name double calc_average( ); double calc_average( ); // Precondition: The values in sum and number are known // Precondition: The values in sum and number are known // Postcondition: The average is calculated by dividing // sum by number. The average is returned to the calling // Postcondition: The average is calculated by dividing // sum by number. The average is returned to the calling // program. // program.