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

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

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

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

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

Chapter 7 - Notes User-Defined Functions II

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

Programming Language. Functions. Eng. Anis Nazer First Semester

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

Chapter Five: Functions. by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

Fundamentals of Programming CS-110. Lecture 2

Functions and Recursion

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

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. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

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

Getting started with C++ (Part 2)

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

Lab Instructor : Jean Lai

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

Objectives. In this chapter, you will:

2 nd Week Lecture Notes

Introduction to Programming EC-105. Lecture 2

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

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

BITG 1233: Introduction to C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

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

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Computer Programming : C++

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

C++ For Science and Engineering Lecture 15

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

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Introduction to C++ (Extensions to C)

Module 7 b. -Namespaces -Exceptions handling

The C++ Language. Arizona State University 1

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

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

Program Organization and Comments

Programming. C++ Basics

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

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

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

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

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Chapter 3 - Functions

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

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

4. C++ functions. 1. Library Function 2. User-defined Function

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Expressions, Input, Output and Data Type Conversions

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Chapter 2 Basic Elements of C++

LECTURE 02 INTRODUCTION TO C++

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Fundamentals of Programming. Lecture 19 Hamed Rasifard

Engineering Problem Solving with C++, Etter/Ingber

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

CMSC 202 Midterm Exam 1 Fall 2015

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

WARM UP LESSONS BARE BASICS

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Fast Introduction to Object Oriented Programming and C++

Data Structures using OOP C++ Lecture 3

Chapter 2: Introduction to C++

Functions, Arrays & Structs

Introduction to C++ Systems Programming

C++ Programming Lecture 11 Functions Part I

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

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Programmer-Defined Functions

Understanding main() function Input/Output Streams

Chapter 2: Overview of C++

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

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Chapter 15 - C++ As A "Better C"

CS242 COMPUTER PROGRAMMING

BITG 1113: Function (Part 2) LECTURE 5

Department of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++

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

a. a * c - 10 = b. a % b + (a * d) + 7 =

3.1. Chapter 3: The cin Object. Expressions and Interactivity

A SHORT COURSE ON C++

CSCE Practice Midterm. Data Types

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

COMP322 - Introduction to C++

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

Transcription:

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

Objectives To understand the concepts of modularity and bottom up testing. To be aware of the use of structured programming. To understand the need for user defined functions. To be able to use correct syntax when declaring and implementing a function. To be able to use stubs and drivers to test functions. To be able to understand the need for and appropriate use of parameters in functions. To be able to understand the difference between value and reference parameters. To understand how functions can be used to design programs. To be able to use functions to get data for programs. To be able to use functions to perform required tasks in programs. To be able to use functions for output. Mr. D. Clausen 2

Objectives To understand what is meant by global identifiers. To understand what is meant by local identifiers. To understand the scope of an identifier. To recognize the appropriate use of global and local identifiers. To be able to understand and control side effects in programs. To be able to use appropriate names for identifiers. To be able to define libraries. To distinguish between library header files and library implementation files. Mr. D. Clausen 3

Today s Lesson The How Reading a Technical Text Determine the central ideas of the text, summarizing the complex concepts, processes, and/or information presented in the text by paraphrasing them in simpler but still accurate terms. Determine the meaning of symbols, key terms, and C++ commands. Mr. D. Clausen 4

Today s Lesson The What User Defined Functions Read Section 4.1 (Pages 127 128) AND Section 4.2 (Pages 129 141) Mr. D. Clausen 5

Today s Lesson The How Part 2 Start with private thinking time. We will use Listen & Compare Structured Discussion with your partner. Groups will share (Explain to your partner) What you learned including: Structured Programming Function Declarations Function Implementations Mr. D. Clausen 6

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. Mr. D. Clausen 7

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 Mr. D. Clausen 8

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). Mr. D. Clausen 9

Advantages of Using Functions 1. To help make the program more understandable 2. To modularize the tasks of the program building blocks of the program 3. Write a module once those lines of source code are called multiple times in the program Mr. D. Clausen 10

Advantages of Using Functions 2 4. While working on one function, you can focus on just that part of the program construct it, debug it, perfect it. 5. Different people can work on different functions simultaneously. 6. If a function is needed in more than one place in a program, or in different programs, you can write it once and use it many times Mr. D. Clausen 11

User Defined Functions User Defined Function A function designed and defined by the programmer. Page130.cpp Mr. D. Clausen 12

How to define a C++ Function? Generally speaking, we define a C++ function in two steps Step #1 declare the function declaration before the main function of the program Step #2 Implement the function after the main function Mr. D. Clausen 13

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. Mr. D. Clausen 14

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); Mr. D. Clausen 15

Function Order Within a Program Comments Preprocessor Directives using namespace std; Constant Declaration & Type Declaration Function Declarations int main( ) { variable declarations main program: function calls } Function Implementations Mr. D. Clausen 16

Structure of a C++ Function A C++ function consists of two parts The function header, and The function body The function header has the following syntax <return value> <name> (<parameter list>) The function body is simply a C++ code enclosed between { } Mr. D. Clausen 17

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

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. Mr. D. Clausen 19

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. Mr. D. Clausen 20

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. Mr. D. Clausen 21

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. Mr. D. Clausen 22

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; } Mr. D. Clausen 23

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 cout<< ----------------- Grade << endl; ------- <<endl; Mr. D. Clausen 24

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 Mr. D. Clausen 25

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

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 Mr. D. Clausen 27

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 Mr. D. Clausen 28

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 Mr. D. Clausen 29

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

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

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 Mr. D. Clausen 32

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 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 Mr. D. Clausen 33

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 Mr. D. Clausen 34

Calling a function by value The function receives a copy of the actual parameter values. The function cannot change the values of the actual parameters. Mr. D. Clausen 35

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 Mr. D. Clausen 36

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 Mr. D. Clausen 37

Calling a function by reference Very useful when we need a function which "returns more than one value". The formal parameter becomes an alias for the actual parameter. The function can change the values of the actual parameters. Mr. D. Clausen 38

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> Mr. D. Clausen 39

Constant Reference Parameter Example string Get_String(const string &prompt) { string data; } cout<<prompt; cin>>data; return data; Mr. D. Clausen 40

The "const" modifier C++ provides us with protection against accidentally changing the values of variables passed by reference with the const operator function declaration: int FindMax(const int&number1, const int&number2); function header: int FindMax(const int& number1, const int& number2); Mr. D. Clausen 41

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) Mr. D. Clausen 42

Putting it all together Sample Program Comparing the cost of pizzas by square inch Pizza.cpp Mr. D. Clausen 43

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

Local Variables Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit You have to initialize the local variable before using it If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable Mr. D. Clausen 45

Scope of Identifiers Scope of an identifier the largest block of code where the identifier is available. Mr. D. Clausen 46

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) Mr. D. Clausen 47

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 Mr. D. Clausen 48