Unit 6. Thinking with Functions

Similar documents
Functions Overview. Functions (aka procedures, subroutines, or methods) are the unit of code decomposition and abstraction

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

Lab Instructor : Jean Lai

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Unit 7. 'while' Loops

Programming Language. Functions. Eng. Anis Nazer First Semester

1. In C++, reserved words are the same as predefined identifiers. a. True

CS2141 Software Development using C/C++ C++ Basics

Object Oriented Design

C/C++ Functions. Mark Redekopp

do { statements } while (condition);

Outline. Why do we write functions? Introduction to Functions. How do we write functions? Using Functions. Introduction to Functions March 21, 2006

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

C++ Programming for Non-C Programmers. Supplement

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Functions. Lecture 6 COP 3014 Spring February 11, 2018

C++ Programming for Non-C Programmers. Supplement

Local and Global Variables

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

Exceptions, Case Study-Exception handling in C++.

A SHORT COURSE ON C++

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Introduction to Programming I COS1511 School of Computing Revision Notes

University of Michigan EECS 183: Elem. Programming Concepts Fall 2011 Exam 1: Part 1: Form 1. Professors: ML Dorf, Elliot Soloway

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Chapter 4 - Notes Control Structures I (Selection)

Chapter 17 - Notes Recursion

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Ch 6. Functions. Example: function calls function

LAB: INTRODUCTION TO FUNCTIONS IN C++

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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

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

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Summary of basic C++-commands

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Using Free Functions

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Understand Execution of a Program

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

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

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

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

Functions, Arrays & Structs

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

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Computer Programming

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

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

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Fundamentals of Programming CS-110. Lecture 2

Problem Solving: Storyboards for User Interaction

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CMSC 202 Midterm Exam 1 Fall 2015

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

CSCE 110 PROGRAMMING FUNDAMENTALS

Using the Xcode Debugger

Introduction to C++ Systems Programming

Unit 14. Passing Arrays & C++ Strings

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

Chapter 1 INTRODUCTION

CS1150 Principles of Computer Science Methods

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

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

C++ Programming Lecture 1 Software Engineering Group

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Name SECTION: 12:45 2:20. True or False (12 Points)

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Intermediate Programming, Spring 2017*

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

C++ Final Exam 2017/2018

C++ basics Getting started with, and Data Types.

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

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

WARM UP LESSONS BARE BASICS

Object oriented programming

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

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

REPETITION CONTROL STRUCTURE LOGO

Review of Important Topics in CS1600. Functions Arrays C-strings

CSE143 Exam with answers MIDTERM #1, 1/26/2001 Problem numbering may differ from the test as given.

1) You want to determine whether time has run out. The following code correctly implements this:

CSC 126 FINAL EXAMINATION FINAL Spring 2012 B. Name (last, First) Instructor. Total Possible. Received

Binomial pricer (1.1)

The following expression causes a divide by zero error:

CSCE Practice Midterm. Data Types

Transcription:

1 Unit 6 Thinking with Functions

Function Decomposition 2 Functions Overview Functions (aka procedures, subroutines, or methods) are the unit of code decomposition and abstraction Map Service ValidateInputs() RetrieveMap() GetOverlayData() Decomposition: Breaking programs into smaller units of code Render() Abstraction: Generalizing an action or concept without specifying how the details are implemented Publish()

3 Function Signatures/Prototypes We think of a function as a blackbox (don't know or care how it does the task internally) where we can provide inputs and get back a value A function has: A name Zero or more input parameters 0 or 1 return (output) values We only specify the type The signature (or prototype) of a function specifies these aspects so others know how to "call" the function a b max int max(int a, int b); Function Signature/Prototype

4 "Functional" Programming While we can write arithmetic expressions directly in C++, let's use functions to perform the same operations. Suppose you are given: add(p, q) // returns p+q sub(p, q) // returns p-q mul(p, q) // returns p*q div(p, q) // returns p/q Convert the following expressions to use functions and no operators (+,-,*,/) Key Ideas: Execution works from inside to outside (i.e. f(g(x)) invokes g(x) first The return value of a function is substituted and used in the larger expression // Add 3 numbers a = x + y + z; // which upholds the order of ops a = add(add(x,y),z); a = add(x,add(y,z)); // Exercise 1 a = x / y + y * z x); a = // Exercise 2 a = x * (y z) / z; a =

5 "Functional" Programming While we can write arithmetic expressions directly in C++, let's practice using functions to perform the same operations. Suppose you are given: add(p, q) // returns p+q sub(p, q) // returns p-q mul(p, q) // returns p*q div(p, q) // returns p/q Convert the following expressions to use functions and no operators (+,-,*,/) Key Ideas: Execution works from inside to outside (i.e. f(g(x)) invokes g(x) first The return value of a function is substituted and used in the larger expression // Add 3 numbers a = x + y + z; // which upholds the order of ops a = add(add(x,y),z); a = add(x,add(y,z)); // Exercise 1 a = x / y + y * z x); a = sub(add(div(x,y),mul(y,z)),x); // Exercise 2 a = x * (y z) / z; a = div(mul(x, sub(y,z)), z);

6 Function call statements Reminder that you can call a function anywhere Result is replaced into bigger expression Take care to "save" the result If you don't save the return value into a variable or use it immediately, the result is lost #include <iostream> #include <cmath> #include <algorithm> using namespace std; int main() // can call functions // in an assignment double res = cos(0); // res = 1.0 // can call functions in an // expression sqrt(2) / 2; // forgot to save result res = sqrt(2) / 2; // res = 1.414/2 cout << max(34, 56) << endl; // outputs 56 return 0; http://www.cplusplus.com/reference/cmath/

7 Reading Documentation Much of programming is calling other library functions which do small pieces of work in an effort to accomplish the overall application Learn to read documentation Documentation at: http://www.cplusplus.com/reference/cmath/ http://www.cplusplus.com/reference/cctype/ http://www.cplusplus.com/reference/cstdlib/

8 User Defined Functions We can define our own functions Good practice is to "declare" your function by placing the prototype (signature) at the top of your code "Define" the function (actual code implementation) anywhere by placing the code in As shown it is defined but never used (no one actually "calls" the max function) #include <iostream> using namespace std; int max(int a, int b); // prototype int main() int x, y, mx; cin >> x >> y; /* Code for main */ int max(int a, int b) if(a > b) return a; else return b;

9 Calling a Function The we can "call" (activate/invoke) our function from any other location in our code as many times as we like Semantics of a function call: Pause the caller code (i.e. main) Pass copies of the arguments to the function (i.e. pass a copy of x and y to a and b) Let the function execute When the function completes we return back to the caller (i.e. main) and resume execution Any return value is substituted in place of the function call Notice 2 sets of parameter names: "Formal names": Generic parameter names used as placeholders to refer to an argument inside the code (e.g. a title like "CEO" or "parent" that refer to a specific person" "Actual" names: True parameters that the formals will reference (e.g. "Jeff Bezos", "Mark Zuckerberg", etc.) #include <iostream> using namespace std; int max(int a, int b); // prototype int main() int x, y, mx; cin >> x >> y; int mx = 1 + max(x, y); // call max cout << mx << endl; cout << max(x, 0) << endl; // call max int max(int a, int b) if(a > b) return a; else return b; Program Output (if user types -5 70): 71 0 0 70

10 Execution Timeline 1. We always start at main() and execute sequentially until a function call or the end of main() 2. When we hit a function call, execution of main pauses and execution of max begins 3. Max will compare the arguments and return the bigger 4. Upon return we go back to where we left off in the previous function and replace the function call with the return value 5. We continue to evaluate the expression in which the function call was made (i.e. 1 + max) 6. We assign the result to mx 7. We continue sequentially until another function call or until the end of main() 8. Another function call again causes main to pause and max begins execution anew 9. Max compares arguments 10. It then returns to the caller (main) and substitutes its return value in the larger expression 2 3 #include <iostream> using namespace std; int max(int a, int b); // prototype int main() 1 int x, y, mx; cin >> x >> y; 7 6 5 int mx = 1 + max(x, y); // call max cout << mx << endl; cout << max(x, 0) << endl; // call max 8 int max(int a, int b) 9 if(a > b) return a; else return b; Program Output (if user types -5 70): 71 0 0 70 10 4

11 Predicate Functions We can write functions that return a bool (true or false) to assert or confirm something about the input These functions can then be called in the condition of an if statement or a loop bool isnegative(double x) return x < 0; bool isdigit(char c) return (c >= '0' && c <= '9'); bool issquare(int s1, int s2, int s3, int s4) return (s1 == s2) && (s2 == s3) && (s3 == s4); int main() int a; char b; char c; cin >> a >> b >> c; if( isnegative(a) ) cout << "Error..neg. #" << endl; if(!isdigit(b)!isdigit(c) ) cout << "Expected 2 digits" << endl; return 0;

12 Exercises Exercises hypotenuse