Chapter 3 Function Basics

Similar documents
CSCI 1061U Programming Workshop 2. Function Basics

Function Call Example

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

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

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

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

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

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

Programmer-Defined Functions

Lab Instructor : Jean Lai

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

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Chapter 3 - Functions

3.2 Predefined Functions Libraries. 3.1 Top Down Design. 3.2 Predefined Functions Libraries. 3.2 Function call. Display 3.

Chapter Four: Loops II

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

Functions and Recursion

C++ Programming Lecture 11 Functions Part I

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

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

Void Functions Call-By-Reference Parameters Using Procedural Abstraction Testing and Debugging General Debugging Techniques

Chapter void Functions. Overview. Functions for All Subtasks. void-functions. Using a void-function. void-function Definition

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Pre- Defined Func-ons in C++ Review for Midterm #1

Programming Language. Functions. Eng. Anis Nazer First Semester

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

Chapter 3 - Functions

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Computing and Statistical Data Analysis Lecture 3

C Functions. 5.2 Program Modules in C

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

Topic 2: C++ Programming fundamentals

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

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.

This watermark does not appear in the registered version - Slide 1

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

CSE 230 Intermediate Programming in C and C++ Functions

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

C++ Basics - 3 Rahul

(created by professor Marina Tanasyuk) FUNCTIONS

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

CIS 130 Exam #2 Review Suggestions

Programming with C++ as a Second Language

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Fundamentals of Structured Programming

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

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

Methods: A Deeper Look

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

Procedural Abstraction and Functions That Return a Value. Savitch, Chapter 4

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Chapter 6 - Notes User-Defined Functions I

Objectives. In this chapter, you will:

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Why Is Repetition Needed?

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

Assertions, pre/postconditions

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

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

6.096 Introduction to C++

Lecture 04 FUNCTIONS AND ARRAYS

Chapter 7 - Notes User-Defined Functions II

Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

CIS133J. Working with Numbers in Java

Chapter 3. Numeric Types, Expressions, and Output

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

Problem Solving with C++

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

Cpt S 122 Data Structures. Introduction to C++ Part II

Chapter 3 - Functions

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

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

Announcements. Lab 1 this week! Homework posted Wednesday (late)

Introduction to Programming

Chapter 2. C++ Basics

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

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

Absolute C++ Walter Savitch

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:

UNIT- 3 Introduction to C++

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

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

Methods CSC 121 Fall 2016 Howard Rosenthal

CSCI Wednesdays: 1:25-2:15 Keller Thursdays: 4:00-4:50 Akerman 211

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

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Transcription:

Chapter 3 Function Basics

Learning Objectives Predefined Functions Those that return a value and those that don t Programmer-defined Functions Defining, Declaring, Calling Recursive Functions Scope Rules Local variables Global constants and global variables Blocks, nested scopes 2

Introduction to Functions Building Blocks of Programs Other terminology in other languages: Procedures, subprograms, methods In C++: functions I-P-O Input Process Output Basic subparts to any program Use functions for these "pieces" 3

Procedural Abstraction Need to know "what" function does, not "how" it does it! Think "black box" Device you know how to use, but not it s method of operation Implement functions like black box User of function only needs: declaration Does NOT need function definition Called Information Hiding Hide details of "how" function does it s job 4

Predefined Functions Libraries full of functions for our use! Two types: Those that return a value Those that do not (void) Must "#include" appropriate library e.g., <cmath>, <cstdlib> (Original "C" libraries) <iostream> (for cout, cin) 5

Using Predefined Functions Math functions very plentiful Found in library <cmath.h> Most return a value (the "answer") Example: theroot = sqrt(9.0); Components: sqrt = name of library function theroot = variable used to assign "answer" to 9.0 = argument or "starting input" for function In I-P-O: I = 9.0 P = "compute the square root" O = 3, which is returned & assigned to theroot 6

The Function Call Back to this assignment: theroot = sqrt(9.0); The expression "sqrt(9.0)" is known as a function call, or function invocation The argument in a function call (9.0) can be a literal, a variable, or an expression The call itself can be part of an expression: bonus = sqrt(sales)/10; A function call is allowed wherever it s legal to use an expression of function s return type 7

A Larger Example: Display 3.1 A Predefined Function That Returns a Value (1 of 2) 8

A Larger Example: Display 3.1 A Predefined Function That Returns a Value (2 of 2) 9

More Predefined Functions #include <cstdlib> Library contains functions like: abs() // Returns absolute value of an int labs() // Returns absolute value of a long int *fabs() // Returns absolute value of a float *fabs() is actually in library <cmath>! Can be confusing Remember: libraries were added after C++ was "born," in incremental phases Refer to appendices/manuals for details 10

More Math Functions pow(x, y) Returns x to the power y double result, x = 3.0, y = 2.0; result = pow(x, y); cout << result; Here 9.0 is displayed since 3.0 2.0 = 9.0 Notice this function receives two arguments A function can have any number of arguments, of varying data types 11

Even More Math Functions: Display 3.2 Some Predefined Functions (1 of 2) 12

Even More Math Functions: Display 3.2 Some Predefined Functions (2 of 2) 13

Predefined Void Functions No returned value Performs an action, but sends no "answer" When called, it s a statement itself exit(1); // No return value, so not assigned This call terminates program void functions can still have arguments All aspects same as functions that "return a value" They just don t return a value! 14

Random Number Generator Return "randomly chosen" number Used for simulations, games rand() Takes no arguments Returns value between 0 & RAND_MAX Scaling Squeezes random number into smaller range rand() % 6 Returns random value between 0 & 5 Shifting rand() % 6 + 1 Shifts range between 1 & 6 (e.g., die roll) 15

Random Number Seed Pseudorandom numbers Calls to rand() produce given "sequence" of random numbers Use "seed" to alter sequence srand(seed_value); void function Receives one argument, the "seed" Can use any seed value, including system time: srand(time(0)); time() returns system time as numeric value Library <time> contains time() functions 16

Random Examples Random double between 0.0 & 1.0: (RAND_MAX rand())/static_cast<double>(rand_max) Type cast used to force double-precision division Random int between 1 & 6: rand() % 6 + 1 "%" is modulus operator (remainder) Random int between 10 & 20: rand() % 10 + 10 17

Programmer-Defined Functions Write your own functions! Building blocks of programs Divide & Conquer Readability Re-use Your "definition" can go in either: Same file as main() Separate file so others can use it, too 18

Components of Function Use 3 Pieces to using functions: Function Declaration/prototype Information for compiler To properly interpret calls Function Definition Actual implementation/code for what function does Function Call Transfer control to function 19

Function Declaration Also called function prototoype An "informational" declaration for compiler Tells compiler how to interpret calls Syntax: <return_type> FnName(<formal-parameter-list>); Example: double totalcost( Placed before any calls In declaration space of main() Or above main() in global space int numberparameter, double priceparameter); 20

Function Definition Implementation of function Just like implementing function main() Example: double totalcost(int numberparameter, double pricep arameter) { const double TAXRATE = 0.05; double subtotal; subtotal = priceparameter * numberparameter; return (subtotal + subtotal * TAXRATE); } Notice proper indenting 21

Function Definition Placement Placed after function main() NOT "inside" function main()! Functions are "equals"; no function is ever "part" of another Formal parameters in definition "Placeholders" for data sent in "Variable name" used to refer to data in definition return statement Sends data back to caller 22

Function Call Just like calling predefined function bill = totalcost(number, price); Recall: totalcost returns double value Assigned to variable named "bill" Arguments here: number, price Recall arguments can be literals, variables, expressions, or combination In function call, arguments often called "actual arguments" Because they contain the "actual data" being sent 23

Function Example: Display 3.5 A Function to Calculate Total Cost (1 of 2) 24

Function Example: Display 3.5 A Function to Calculate Total Cost (1 of 2) 25

Alternative Function Declaration Recall: Function declaration is "information" for compiler Compiler only needs to know: Return type Function name Parameter list Formal parameter names not needed: double totalcost(int, double); Still "should" put in formal parameter names Improves readability 26

Parameter vs. Argument Terms often used interchangeably Formal parameters/arguments In function declaration In function definition s header Actual parameters/arguments In function call Technically parameter is "formal" piece while argument is "actual" piece* *Terms not always used this way 27

Functions Calling Functions We re already doing this! main() IS a function! Only requirement: Function s declaration must appear first Function s definition typically elsewhere After main()"s definition Or in separate file Common for functions to call many other functions Function can even call itself à "Recursion" 28

Boolean Return-Type Functions Return-type can be any valid type Given function declaration/prototype: bool appropriate(int rate); And function s definition: bool appropriate (int rate) { return (((rate>=10)&&(rate<20)) (rate==0); } Returns "true" or "false" Function call, from some other function: if (appropriate(entered_rate)) cout << "Rate is valid\n"; 29

Declaring Void Functions Similar to functions returning a value Return type specified as "void" Example: Function declaration/prototype: void showresults( double fdegrees, double cdegrees); Return-type is "void" Nothing is returned 30

Declaring Void Functions Function definition: void showresults(double fdegrees, double cdegrees) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1); cout << fdegrees << " degrees fahrenheit equals \n" << cdegrees << " degrees celsius.\n"; } Notice: no return statement Optional for void functions 31

Calling Void Functions Same as calling predefined void functions From some other function, like main(): showresults(degreesf, degreesc); showresults(32.5, 0.3); Notice no assignment, since no value returned Actual arguments (degreesf, degreesc) Passed to function Function is called to "do it s job" with the data passed in 32

More on Return Statements Transfers control back to "calling" function For return type other than void, MUST have return statement Typically the LAST statement in function definition return statement optional for void functions Closing } would implicitly return control from void function 33

Preconditions and Postconditions Similar to "I-P-O" discussion Comment function declaration: void showinterest(double balance, double rate); //Precondition: balance is nonnegative account balance // rate is interest rate as percentage //Postcondition: amount of interest on given balance, // at given rate Often called Inputs & Outputs 34

main(): "Special" Recall: main() IS a function "Special" in that: One and only one function called main() will exist in a program Who calls main()? Operating system Tradition holds it should have return statement Value returned to "caller" à Here: operating system Should return "int" or "void" 35

Scope Rules Local variables Declared inside body of given function Available only within that function Can have variables with same names declared in different functions Scope is local: "that function is it s scope" Local variables preferred Maintain individual control over data Need to know basis Functions should declare whatever local data needed to "do their job" 36

Global Constants and Global Variables Declared "outside" function body Global to all functions in that file Declared "inside" function body Local to that function Global declarations typical for constants: const double TAXRATE = 0.05; Declare globally so all functions have scope Global variables? Possible, but SELDOM-USED Dangerous: no control over usage! 37

Blocks Declare data inside compound statement Called a "block" Has "block-scope" Note: all function definitions are blocks! This provides local "function-scope" Loop blocks: for (int ctr=0;ctr<10;ctr++) { sum+=ctr; } Variable ctr has scope in loop body block only 38

Nested Scope Same name variables declared in multiple blocks Very legal; scope is "block-scope" No ambiguity Each name is distinct within its scope 39

Summary 1 Two kinds of functions: "Return-a-value" and void functions Functions should be "black boxes" Hide "how" details Declare own local data Function declarations should self-document Provide pre- & post-conditions in comments Provide all "caller" needs for use 40

Summary 2 Local data Declared in function definition Global data Declared above function definitions OK for constants, not for variables Parameters/Arguments Formal: In function declaration and definition Placeholder for incoming data Actual: In function call Actual data passed to function 41