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

Similar documents
Introduction to Programming

Chapter 3 - Functions

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

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

C++ Programming Lecture 11 Functions Part I

Functions and Recursion

Chapter 3 - Functions

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

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

Functions. Systems Programming Concepts

Functions and Recursion

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

C Functions. 5.2 Program Modules in C

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

C Functions. Object created and destroyed within its block auto: default for local variables

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

CSE123. Program Design and Modular Programming Functions 1-1

Methods: A Deeper Look

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Chapter 7 Array. Array. C++, How to Program

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Introduction to C++ Systems Programming

Control Structures of C++ Programming (2)

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

Using Free Functions

CT 229 Java Syntax Continued

Fundamentals of Programming & Procedural Programming

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

Chapter 9 Classes : A Deeper Look, Part 1

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

Chapter 3 - Functions

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

6.5 Function Prototypes and Argument Coercion

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

(created by professor Marina Tanasyuk) FUNCTIONS

Chapter 6 - Notes User-Defined Functions I

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

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

CS110: PROGRAMMING LANGUAGE I

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

1001ICT Introduction To Programming Lecture Notes

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

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

Lecture 04 FUNCTIONS AND ARRAYS

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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.

Programming Language. Functions. Eng. Anis Nazer First Semester

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Computing and Statistical Data Analysis Lecture 3

Control Statements: Part Pearson Education, Inc. All rights reserved.

Downloaded from Chapter 2. Functions

Chapter 2. Outline. Simple C++ Programs

Introduction to C++ Introduction to C++ 1

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

Lecture 5: Methods CS2301

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

Functions and Recursion

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

C Functions Pearson Education, Inc. All rights reserved.

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

ECET 264 C Programming Language with Applications

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

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

C Programming for Engineers Functions

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

Lab Instructor : Jean Lai

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Functions. Introduction :

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

C Programs: Simple Statements and Expressions

Fundamentals of Programming Session 13

Fundamentals of Programming Session 25

Engineering Problem Solving with C++, Etter/Ingber

Chapter 5 C Functions

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

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Chapter 2 - Control Structures

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

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

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

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

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

A SHORT COURSE ON C++

Computer Science & Engineering 150A Problem Solving Using Computers

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

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

C++ Programming: Functions

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

Summary of basic C++-commands

LECTURE 06 FUNCTIONS

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

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

Multiple-Precision Arithmetic Library exflib (C++) FUJIWARA Hiroshi

What is a Function? What are functions good for?

Transcription:

Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide and Conquer technique Allow programs to be broken down into smaller pieces. This makes programs easier to read and maintain. Statements in function bodies are written only once Reused from perhaps several locations in a program Hidden from other functions Avoid repeating code Spring 2016 CISC1600 Yanjun Li 2 1

Functions Functions you have used: main() starting point of a program, calls other functions Other function: std::setprecision( x ) Spring 2016 CISC1600 Yanjun Li 3 Define A Function Definition of a method: Header : Return type, Function Name, Parameter(s) [ type and name pair ]. Body : a collection of statements. Example: int addtwonumbers (int numberone, int numbertwo ) { int sum; sum = numberone + numbertwo; } return sum; Spring 2016 CISC1600 Yanjun Li 4 2

Function Prototype Also called a function declaration Indicates to the compiler: Type of data returned by the function Function Signature Name of the function Parameters the function expects to receive Number of parameters Types of those parameters Order of those parameters Example: int addtwonumbers(int, int); Function prototype is provided before the function is invoked. Spring 2016 CISC1600 Yanjun Li 5 User A Function Invoked with function name and parameters Example: int x, y, sum; x = 4; y = 5; //invoke funtion addtwonumbers to do the addition sum = addtwonumbers(x, y); Spring 2016 CISC1600 Yanjun Li 6 3

Another Example Define the Function : void displaymessage (int number) { cout<< "The result is "<< number <<endl; } Invoke the Function : displaymessage ( sum ); Output : The result is 9 Spring 2016 CISC1600 Yanjun Li 7 One More Example Define the Function : void displaywelcomemessage ( ) { cout<< Welcome to The World of C++! "<<endl; } Invoke the Function : displaywelcomemessage ( ); Output : Welcome to The World of C++! Spring 2016 CISC1600 Yanjun Li 8 4

How Function Call Works (1) Spring 2016 CISC1600 Yanjun Li 9 How Function Call Works (2) Spring 2016 CISC1600 Yanjun Li 10 5

How Function Call Works (3) Spring 2016 CISC1600 Yanjun Li 11 Math Library Functions Have function prototypes placed in header files Can be reused in any program that includes the header file and that can link to the function s object code Example: sqrt in <cmath> header file sqrt( 900.0 ) Spring 2016 CISC1600 Yanjun Li 12 6

Useful Standard Library Function Standard library function std::pow( ) Calculates an exponent Function takes two arguments of type double and returns a double value. Requires header file <cmath> Example : #include <cmath> using std::pow; //in main function double x,y,result; x=2; y=2; result = pow(x,y); Calculates the value of x raised to the y th power Spring 2016 CISC1600 Yanjun Li 13 Function Description Example ceil( x ) cos( x ) rounds x to the smallest integer not less than x trigonometric cosine of x (x in radians) ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0 exp( x ) exponential function e x exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( x ) fmod( x, y ) log( x ) rounds x to the largest integer not greater than x remainder of x/y as a floating-point number natural logarithm of x (base e) floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( 2.6, 1.2 ) is 0.2 log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to power y (x y ) pow( 2, 7 ) is 128 pow( 9,.5 ) is 3 sin( x ) sqrt( x ) tan( x ) trigonometric sine of x (x in radians) square root of x (where x is a nonnegative value) trigonometric tangent of x (x in radians) sin( 0.0 ) is 0 sqrt( 9.0 ) is 3.0 tan( 0.0 ) is 0 Fig. 6.2 Math library functions Spring 2016 CISC1600 Yanjun Li 14 7

Default Arguments A default value to be passed to a parameter Used when the function call does not specify an argument for that parameter Must be the rightmost argument(s) in a function s parameter list Should be specified with the first occurrence of the function name Typically the function prototype It is a compilation error to specify default arguments in both a function s prototype and header. Spring 2016 CISC1600 Yanjun Li 15 1 // Fig. 6.22: fig06_22.cpp 2 // Using default arguments. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 // function prototype that specifies default arguments 8 int boxvolume( int length = 1, int width = 1, int height = 1 ); 9 10 int main() 11 { 12 // no arguments--use default values for all dimensions 13 cout << "The default box volume is: " << boxvolume(); 14 15 // specify length; default width and height 16 cout << "\n\nthe volume of a box with length 10,\n" 17 << "width 1 and height 1 is: " << boxvolume( 10 ); 18 19 // specify length and width; default height 20 cout << "\n\nthe volume of a box with length 10,\n" 21 << "width 5 and height 1 is: " << boxvolume( 10, 5 ); 22 23 // specify all arguments 24 cout << "\n\nthe volume of a box with length 10,\n" 25 << "width 5 and height 2 is: " << boxvolume( 10, 5, 2 ) 26 << endl; 27 return 0; // indicates successful termination 28 } // end main Default arguments Calling function with no arguments Calling function with one argument Calling function with two arguments Calling function with three arguments Spring 2016 CISC1600 Yanjun Li 16 8

29 30 // function boxvolume calculates the volume of a box 31 int boxvolume( int length, int width, int height ) 32 { 33 return length * width * height; 34 } // end function boxvolume The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100 Note that default arguments were specified in the function prototype, so they are not specified in the function header Spring 2016 CISC1600 Yanjun Li 17 Local Variable in Function The variables defined local to the block of the function would be accessible only within the block of the function and not outside the function. Example: int functionone(int x,int y) { int z; z=x+y; return z; } Spring 2016 CISC1600 Yanjun Li 18 9

Global Variables Created by placing variable declarations outside any function definition Retain their values throughout the execution of the program Can be referenced by any function that follows their declarations or definitions in the source file Spring 2016 CISC1600 Yanjun Li 19 Scope Rules (1) Scope Portion of the program where an identifier can be used We discuss two scopes for an identifier File scope Block scope Spring 2016 CISC1600 Yanjun Li 20 10

Scope Rules (2) File scope For an identifier declared outside any function Such an identifier is known in all functions from the point at which it is declared until the end of the file Global variables, function definitions and function prototypes placed outside a function all have file scope Spring 2016 CISC1600 Yanjun Li 21 Scope Rules (3) Functions in the same scope (File Scope) must have unique signatures The scope of a function is the region of a program in which the function is known and accessible It is a compilation error if two functions in the same scope have the same signature but different return types. Spring 2016 CISC1600 Yanjun Li 22 11

Scope Rules (4) Block scope Identifiers declared inside a block have block scope Block scope begins at the identifier s declaration Block scope ends at the terminating right brace (}) of the block in which the identifier is declared Local variables and function parameters have block scope The function body is their block Any block can contain variable declarations Spring 2016 CISC1600 Yanjun Li 23 Scope Rules (5) Block scope Identifiers in an outer block can be hidden when a nested block has a local identifier with the same name Example: int x= 10; for (int i=0; i<10; i++) { int x = 5+ i; } Spring 2016 CISC1600 Yanjun Li 24 12

References and Reference Parameters (1) Two ways to pass arguments to functions Pass-by-value A copy of the argument s value is passed to the called function Changes to the copy do not affect the original variable s value in the caller Prevents accidental side effects of functions Pass-by-reference Gives called function the ability to access and modify the caller s argument data directly Spring 2016 CISC1600 Yanjun Li 25 References and Reference Parameters (2) Reference Parameter An alias for its corresponding argument in a function call & placed after the parameter type in the function prototype and function header Example int funcname(int &count) in a function header Pronounced as count is a reference to an int Spring 2016 CISC1600 Yanjun Li 26 13

References and Reference Parameters (3) Parameter name in the body of the called function actually refers to the original variable in the calling function When the function is invoked, simply mention the variable by name to pass it by reference. Example int x, y; y = funcname(x); Spring 2016 CISC1600 Yanjun Li 27 Reference Reproduced from the Cyber Classroom for C++, How to Program, 5/e by Deitel & Deitel. Reproduced by permission of Pearson Education, Inc. Spring 2016 CISC1600 Yanjun Li 28 14