Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Similar documents
Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Introduction To Computer Programming C++ Mr. Clausen Program C11A, C11B

Honors Computer Science C++ Mr. Clausen Program 4A, 4B, 4C (4D, 4G)

Honors Computer Science C++ Mr. Clausen Program 4A, 4B, 4C, 4D, 4G

Chapter 4 Computer Science with C++ Name: Review Worksheet A Mr. Ferwerda

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Honors Computer Science C++ Mr. Clausen Program 3A, 3B, 3C

Chapter 7 - Notes User-Defined Functions II

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Honors Computer Science C++ Mr. Clausen Program 6A, 6B, 6C, & 6G

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Enumerated Types. Mr. Dave Clausen La Cañada High School

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

The C++ Language. Arizona State University 1

Programming. C++ Basics

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does

Program Organization and Comments

Fundamentals of Programming CS-110. Lecture 2

TDDE18 & 726G77. Functions

Chapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.

Chapter 4. Procedural Abstraction and Functions That Return a Value

Objectives. In this chapter, you will:

1. Word Analysis: (Which nouns suggest a need for memory (a variable) and which verbs suggest a need for action (a function maybe).

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Outline. Functions. Functions. Predefined Functions. Example. Example. Predefined functions User-defined functions Actual parameters Formal parameters

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Problem Solving with C++

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Functions and Recursion

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Absolute C++ Walter Savitch

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Introduction to Programming EC-105. Lecture 2

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Programming Language. Functions. Eng. Anis Nazer First Semester

Computer Programming : C++

BITG 1233: Introduction to C++

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names

COMP322 - Introduction to C++

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

2 nd Week Lecture Notes

C++ Programming Lecture 11 Functions Part I

CPE Summer 2015 Exam I (150 pts) June 18, 2015

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

CS201 Some Important Definitions

Lab # 02. Basic Elements of C++ _ Part1

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Getting started with C++ (Part 2)

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Chapter 2. Procedural Programming

CS201 Latest Solved MCQs

Chapter 3 - Functions

Functions. Function Prototypes. Function prototype is needed if the function call comes before the function definition in the program.

Chapter 2 Basic Elements of C++

Chapter 2: Introduction to C++

Programmer-Defined Functions

Introduction to C++ (Extensions to C)

6. C++ Subprograms David Keil CS I slides 7/03 1

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

DELHI PUBLIC SCHOOL TAPI

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

Chapter 6 - Notes User-Defined Functions I

UNIT- 3 Introduction to C++

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

LECTURE 02 INTRODUCTION TO C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to C++ Systems Programming

Computing and Statistical Data Analysis Lecture 3

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

Lab Instructor : Jean Lai

Question 2. [5 points] Given the following symbolic constant definition

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Creating a C++ Program

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

BITG 1113: Function (Part 2) LECTURE 5

Expressions, Input, Output and Data Type Conversions

CS242 COMPUTER PROGRAMMING

CHAPTER 4 FUNCTIONS. 4.1 Introduction

LAB 4.1 Relational Operators and the if Statement

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

Functions. Introduction :

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

Transcription:

Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School

Modular programming Program Design Stepwise refinement of main tasks into subtasks. Modules or subprograms that contain all definitions and declarations necessary to solve the subtask. The lowest level of a C++ program is a function. Abstract Data Type: higher level of design with a class of objects, defined properties and set of operations for processing the objects. 4/13/2011 Mr. D. Clausen 2

Program Design 2 Modularity The organization of a program into simple tasks that work as independent units Bottom Up Testing Testing each module independently (or even writing your program one function at a time). Structured Programming independent modules with flow of control & data 4/13/2011 Mr. D. Clausen 3

Structured Design Program Design 3 The process of designing the modules and specifying the flow of data between them. Information is shared from parameter lists: formal and actual parameters (function arguments). Organization of modules and flow of parameters is done through the main program (main function). 4/13/2011 Mr. D. Clausen 4

User Defined Functions User Defined Function A function designed and defined by the programmer. Page130.cpp Page130.txt 4/13/2011 Mr. D. Clausen 5

Function Declarations Function Declaration Function name, number and type of arguments it expects and type of value it returns (if any). General Form: <return type> <Function_Name> (<arguments>); function name is descriptive valid identifier return type, declares the one data type returned by the function Style: include comments regarding input & output. 4/13/2011 Mr. D. Clausen 6

Function Declaration Example //Function: Sqrt //Compute the square root of a double precision floating point number // //Input: a nonnegative double precision floating point number //Output: a nonnegative double precision floating point number that represents the square root of the number received double Sqrt (double x); 4/13/2011 Mr. D. Clausen 7

Function Order Within a Program Comments Preprocessor Directives Constant Declaration & Type Declaration Function Declarations int main( ) { main program: function calls } Function Implementations 4/13/2011 Mr. D. Clausen 8

Function Implementations Function Implementation a complete description of the function double Sqr (double x) { return x*x; } //no semicolon here 4/13/2011 Mr. D. Clausen 9

Function heading Function Headings the first line of the function implementation containing the function s name, parameter declarations, and return type looks like the function declaration minus the semicolon function heading must match the function declaration in type and parameter list types and order. 4/13/2011 Mr. D. Clausen 10

Function Headings 2 Formal Parameters The arguments in the function heading. Actual Parameters The arguments in the function call. The number of formal and actual parameters must match and should match in order and type. 4/13/2011 Mr. D. Clausen 11

Function Heading General Form General Form <return type> <Function_Name> (<formal parameter list>) function name is a valid identifier use descriptive names a value may need to be returned if a return type is declared return type declares the data type of the function the formal parameters are pairs of data types and identifier names separated by commas. 4/13/2011 Mr. D. Clausen 12

Value Returning Functions Declare function type of value to be returned double, int, char, etc. Only ONE value is returned use return command as last line of function don t use pass by reference parameters don t use cout statements like mathematical function, calculates 1 answer like a function in Pascal Style: Use Noun names that start w/ a capital letter 4/13/2011 Mr. D. Clausen 13

//Function: Cube Function Example // Computes the cube of an integer // //Input: a number Function Declaration //Output: a number representing the cube of the input number double Cube (double x); double Cube (double x) { return x*x*x; } Function Implementation 4/13/2011 Mr. D. Clausen 14

Function Example 2 // Function: compute price per square inch // Compute the price per square inch of pizza // // Input: cost and size of pizza // Output: price per square inch double Price_Per_Square_Inch(double cost, int size); double Price_Per_Square_Inch(double cost, int size) { double radius, area; Function Declaration } radius = size / 2; area = PI * sqr(radius); return cost / area; Function Implementation 4/13/2011 Mr. D. Clausen 15

Stub Programming Stub Programming the use of incomplete functions to test data transmission between them. Contains declarations and rough implementations of each function. Tests your program logic and values being passed to and from subprograms. Roots1.cpp Roots2.cpp Roots.cpp Roots1.txt Roots2.txt Roots.txt 4/13/2011 Mr. D. Clausen 16

Main Driver Main Driver another name for the main function when subprograms are used. The driver can be modified to test functions in a sequential fashion. The main driver is a function factory add a function declaration, then a rough implementation test the function stub by calling the function from the main driver 4/13/2011 Mr. D. Clausen 17

Driver Example // Program file: driver.cpp P.137 #include <iostream.h> int main() { int data; //Start //Start with with a simple simple program program } cout << "Enter an integer: "; cin >> data; return 0; 4/13/2011 Mr. D. Clausen 18

Driver Example 2 // Program file: driver.cpp driver.txt //P.137-138 #include <iostream.h> int main() { int data; Add Add a function function declaration, declaration, rough rough implementation, implementation, and and a function function call call to to test test one one function. function. } cout << "Enter an integer: "; cin >> data; cout << "The square is " << Sqr(data) << endl; return 0; 4/13/2011 Mr. D. Clausen 19

Driver: Test and Fill in Details Once you have tested the function declaration, call, and implementation by sending and returning the same value, fill in the details of the function. In the driver.cpp example, this means replace: return x with return x*x driver2.cpp driver2.txt 4/13/2011 Mr. D. Clausen 20

Void Functions Some functions need data to do their work, but return no values. Other functions need NO data AND return no values. These are called void functions (like a Procedure in Pascal). The function call appears on a line by itself and not as a part of a statement. Style: Use function names that include action verbs and use a capital letter to begin each word. 4/13/2011 Mr. D. Clausen 21

Void Function Example void Display_Results (int result1, int result2, int result3) //This is used to send your output to the screen // The output stream. { cout<< The first result is: <<result1<<endl; cout<< The second result is: <<result2<<endl; cout<< The third result is: <<result3<<endl; } 4/13/2011 Mr. D. Clausen 22

Void Function without void Display_Header( ) { } Parameters //Takes no parameters and returns no values //The sole purpose is to display text on the output screen. //Perhaps a header, a logon greeting, or whose output. cout<< Grades for Computer Science 110 << endl; cout<<endl; cout<< Student Name Grade << endl; cout<< ----------------- ------- <<endl; 4/13/2011 Mr. D. Clausen 23

Formal and Actual Parameters Formal parameters the parameters listed in the function declaration and implementation they indicate the form that the parameters will take, a data type and identifier paired together Actual parameters Area.cpp Area.txt the parameters in the function call which must match the formal parameter list in order & type choose synonyms for names of actual & formal or same name 4/13/2011 Mr. D. Clausen 24

Value Parameters Value Parameters (Passed by Value) values passed only from caller to a function think of this as a one way trip a copy of the actual parameters are made and sent to the function where they are known locally. any changes made to the formal parameters will leave the actual parameters unchanged at the end of the function, memory is deallocated for the formal parameters. Area.cpp Area.txt 4/13/2011 Mr. D. Clausen 25

Reference Parameters Reference Parameters (Pass by Reference) when you want a function to return more than one value Use a void function with reference parameters. This will be similar to a Pascal procedure. Like a two way trip for more than one parameter The value of the parameter can be changed by the subprogram. No copy of the parameters are made 4/13/2011 Mr. D. Clausen 26

Reference Parameters 2 Only the address of the actual parameter is sent to the subprogram. Format for formal reference parameters <type name> &<formal parameter name> void Get_Data(int &length, int &width); Alias: two or more identifiers in a program that refer to the same memory location Remember: avoid reference parameters in value returning functions don t send constants to a function with reference parameters Page147Swap.cpp P147Swap.txt 4/13/2011 Mr. D. Clausen 27

Constant Reference Parameters Constant Reference declare the formal parameter so that the actual parameter is passed by reference, but cannot change within the function Format for Constant Reference Parameters const <type name> &<parameter name> 4/13/2011 Mr. D. Clausen 28

Constant Reference Parameter Example apstring Get_String(const apstring &prompt) { apstring data; } cout<<prompt; cin>>data; return data; 4/13/2011 Mr. D. Clausen 29

Choosing a Parameter Method When the actual parameter must be changed, or you need a two way trip use a reference parameter //Get_Data or Input Function & When the value should NOT be changed (a one way trip ) and the data size is small, declare as a value parameter. //Calculations When the value should NOT be changed and the data size is large, use a constant reference parameter. //Output Functions (const double & area) 4/13/2011 Mr. D. Clausen 30

Putting it all together Sample Program Comparing the cost of pizzas by square inch Pizza.cpp Pizza.txt 4/13/2011 Mr. D. Clausen 31

Local and Global Identifiers Global Identifiers those that are declared before the main program Good Style limits global identifiers to: constants type declarations function declarations Local Identifiers Please use global constants! Don t use global variables!!! declared between { and } of main or subprogram 4/13/2011 Mr. D. Clausen 32

Scope of Identifiers Scope of an identifier the largest block of code where the identifier is available. 4/13/2011 Mr. D. Clausen 33

Programmer Defined Libraries To create your own libraries: Declare all functions including comments and save as ####lib.h or mylib.h Implement all functions and save as ####lib.cpp or mylib.cpp 4/13/2011 Mr. D. Clausen 34

Library Header File Example Use #ifndef <file name> asks if the file identifier has been defined if it has been defined, it skips to #endif statement (prevents multiple redefining) if it hasn t been defined, the preprocessor will see the #define directive after preprocessing the file myinput.h myinputh.txt 4/13/2011 Mr. D. Clausen 35

Library Implementation File Example Contains all function implementations complete with local variables and formal parameters #include myinput.h to include the header file with the function declarations Need a program to call my library Build a project to include all parts myinput.cpp myinput.txt 4/13/2011 Mr. D. Clausen 36

Program Main Driver for my library #include myinput.h use quotes, not angle brackets < > Call the functions from the Main Driver Don t forget to make and build a project to link all the parts. In this case, don t forget: #include apstring.h apstring.cpp testmyin.cpp testmyin.txt testmyin.ide 4/13/2011 Mr. D. Clausen 37

Function Overloading Function Overloading When two or more functions have the same name. Function Overloading can only be allowed when the function declarations differ by the number of parameters they use, by using different data types for at least one parameter, or belong to different classes (more on this later) 4/13/2011 Mr. D. Clausen 38

Function Overloading Examples Function Declarations double Triangle_Area (double base, double height); //Area = ½ * Base * Height double Triangle_Area (double side1, double side2, double side3); //Hero s Formula using three sides for the area 4/13/2011 Mr. D. Clausen 39