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

Similar documents
CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Functions and Recursion

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

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

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

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

Introduction to C++ Systems Programming

Chapter 3 - Functions

Lab Instructor : Jean Lai

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

Chapter 3 - Functions

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

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

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

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

Pointers and Strings. Adhi Harmoko S, M.Komp

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 3 - Functions

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

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

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

C++ Programming Lecture 11 Functions Part I

Pointers and Strings Prentice Hall, Inc. All rights reserved.

6.5 Function Prototypes and Argument Coercion

Computer Science II Lecture 1 Introduction and Background

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

CS242 COMPUTER PROGRAMMING

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

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

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

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Fast Introduction to Object Oriented Programming and C++

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

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

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

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

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

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

Functions. Introduction :

Functions and Recursion

EECS402 Lecture 02. Functions. Function Prototype

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Introduction to Programming

University of Dublin

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

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.

Arrays. Week 4. Assylbek Jumagaliyev

CS 376b Computer Vision

Introduction to Programming

C Pointers. 7.2 Pointer Variable Definitions and Initialization

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Array Elements as Function Parameters

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

True or False (12 Points)

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Chapter 3 Problem Solving and the Computer

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

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

IS 0020 Program Design and Software Tools

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Exercise 1.1 Hello world

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Introduction to C ++

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Local and Global Variables

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

Chapter 4: Subprograms Functions for Problem Solving. 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

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Module Contact: Dr Pierre Chardaire, CMP Copyright of the University of East Anglia Version 1

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

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:

Summary of basic C++-commands

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:

REPETITION CONTROL STRUCTURE LOGO

Computing and Statistical Data Analysis Lecture 3

C++ For Science and Engineering Lecture 2

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

Scientific Computing

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

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

Introduction to Programming using C++

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

IS 0020 Program Design and Software Tools

Global & Local Identifiers

Introduction to C++ (Extensions to C)

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

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

PIC 10A. Lecture 17: Classes III, overloading

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

Midterm Exam. Sample Solutions

Your first C++ program

Transcription:

Functions Functions are defined as follows: return-value-type function-name( parameter-list ) { local declarations and statements Example: int square( int y ) { return y * y; 1 Function Prototypes Function prototype is needed if the function call comes before the function definition in the program. Function prototype consists of Return type (default int) Function name Parameters 3 1 // Fig. 3.3: fig03_03.cpp 2 // Creating and using a programmer-defined function 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int square( int ); // function prototype 10 int main() 11 { 12 for ( int x = 1; x <= 10; x++ ) 13 cout << square( x ) << " "; 1 15 cout << endl; 16 return 0; 1 18 1 // Function definition 20 int square( int y ) 21 { 22 return y * y; 23 1 16 25 36 6 81 100 2 Functions with Empty Parameter Lists Empty parameter lists Either writing void or leaving a parameter list empty indicates that the function takes no arguments void print(); or void print( void ); Function print takes no arguments and returns no value 1

1 // Fig. 3.18: fig03_18.cpp 2 // Functions that take no arguments 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 void function1(); void function2( void ); 10 11 int main() 12 { 13 function1(); 1 function2(); 15 16 return 0; 1 18 1 void function1() 20 { 21 cout << "function1 takes no arguments" << endl; 22 23 2 void function2( void ) 25 { 26 cout << "function2 also takes no arguments" << endl; 2 function1 takes no arguments function2 also takes no arguments 5 1 // Fig. 3.23: fig03_23.cpp 2 // Using default arguments 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int boxvolume( int length = 1, int width = 1, int height = 1 ); 10 int main() 11 { 12 cout << "The default box volume is: " << boxvolume() 13 << "\n\nthe volume of a box with length 10,\n" 1 << "width 1 and height 1 is: " << boxvolume( 10 ) 15 << "\n\nthe volume of a box with length 10,\n" 16 << "width 5 and height 1 is: " << boxvolume( 10, 5 ) 1 << "\n\nthe volume of a box with length 10,\n" 18 << "width 5 and height 2 is: " << boxvolume( 10, 5, 2 ) 1 << endl; 20 21 return 0; 22 23 2 // Calculate the volume of a box 25 int boxvolume( int length, int width, int height ) 26 { 2 return length * width * height; 28 Default Arguments The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 If function parameter is omitted, it gets a default value Rightmost parameters go to their defaults Defaults are set in function prototypes Example: 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 Notice how the rightmost values are defaulted. int function( int x = 1, int y = 2, int z = 3 ); 6 8 2

Function Overloading Function overloading Having functions with same name and different parameters int square( int x) {return x * x; float square(float x) { return x * x; Program chooses function by signature signature determined by function name and parameter types Summary of C++ Functions What are they? Functions are subprograms that return a value given some arguments. The square root function, sqrt(argument), is an example of a function. C++ provides access to many standard functions via the #include directive. You have the capability to write your own functions. 11 1 // Fig. 3.25: fig03_25.cpp 2 // Using overloaded functions 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int square( int x ) { return x * x; 10 double square( double y ) { return y * y; 11 12 int main() 13 { 1 cout << "The square of integer is " << square( ) 15 << "\nthe square of double.5 is " << square(.5 ) 16 << endl; 1 18 return 0; 1 The square of integer is The square of double.5 is 56.25 10 Summary of C++ Functions How do you implement your own functions? First, place a function prototype at the beginning of your program, before main(). Syntax: return_type fun_name(arg_type arg_name[,]); Examples: long AddAbsolute(int a, int b); double CubeRoot(double); void Display_Menu(void); 12 3

Summary of C++ Functions Then place the function implementation after the closing brace of main(){. Syntax: return_type fun_name(arg_type arg_name[,]){ function_body Example: int main(){ long AddAbsolute(int a, int b){ Summary of C++ Functions Functions with a return_type other than void should have a return statement. To call a function, place the function reference in an expression of the calling module, e.g. x = CubeRoot(a+b) + AddAbsolute(c,d); Do not output a function that has a return_type of void. Example: void printmenu(void); cout<< printmenu(); // DO NOT DO!! 13 15 Example #include <iostream> using namespace std; //Function Prototypes long AddAbsolute(int a, int b); double CubeRoot(double); //Main Function int main(){ //Function Implementations long AddAbsolute(int a, int b){ double CubeRoot(double x){ Summary of C++ Functions Do not use a function that has a return_type of void in a mathematical operation. Example: void printmenu(void); int x = printmenu(); // DO NOT DO!! See the examples of function implementations on the next page. 1 16

Function Example 1 Objective : Returns the maximum of a and b Prototype : int MaxVal( int, int ); int MaxVal(int a, int b) { if(a>b) return a; else return b; Function Example 3 Objective : Returns true if the input is an odd # Prototype : bool Odd( int ); bool Odd(int n) { if ((n % 2) == 1) return true; else return false; 1 1 Function Example 2 Objective : Returns true if the input is a prime # Prototype : bool isprime( int ); bool isprime( int n ) { bool prime = true; for (int i=2; i<=n-1; i++) { if (n%i == 0) prime = false; return prime; Notes about Functions Every function must have a name, using the same naming rules as variables. To differentiate functions from variables you may want to capitalize function names. Example: cube_root = Cube_Root(alpha); Functions may have zero or more arguments; parentheses are always required. Use the return statement to return a value from a function. Several alternative return statements are allowed, but only one return is suggested. 18 20 5

Notes about Functions A function with a return type of void returns nothing. A return statement is not needed. Use voided functions to perform tasks, like get_data, solve_problem or display_results. Typically, voided functions are called with a simple expression statement Function Example The complete implementation of a function may replace its prototype. This practice is generally discouraged. Objective : Returns true if the input is an odd # Prototype and #include <iostream> using namespace std; bool Odd ( int n ) { return n%2; Example: get_data(x,y,z); 21 int main(){ 23 Notes about Functions Function Example 5 Never define a function in another function. main() is a function. If you do not specify a return type, int is assumed. For clarity, make functions small, not more than one screen. Objective : Returns random numbers between 0 and 1 Prototype : double Random( unsigned long ); double Random(unsigned long seed){ seed = 238285 * seed; return double(seed) / 2625.0; 22 2 6

Function Example 6 Objective : Displays the menu Prototype : void Display_Menu( void ); void Display_Menu(void) { cout << endl << MAIN MENU << endl; cout << 0 - quit << endl; cout << 1 - Read a file << endl; cout << 2 - Print a record << endl; Function Example 8 Objective : Returns n!/(n-r)! Prototype : int Permutation( int, int ); int Permutation(int n, int r) { int perm = 1; for (int i=n-r+1; i<=n; i++) perm *= i; return perm; 25 2 Function Example Objective : Computes the area of a triangle given 2 sides and an angle Prototype : double SSA( double, float, double angle ); #define M_PI 3.11526535832386 double SSA(double s1, float s2, double angle) { const double RPD = M_PI/180.0; // radians/degree return 0.5 * s1 * s2 * sin(angle * RPD); Function Example 8 Objective : Returns n!/(n-r)! Prototype : int Permutation( int, int ); int Permutation(int n, int r) { return nfact(n)/nfact(n-r); 26 28

Function Example Objective : Returns n! / (r!(n-r)!) Prototype : int Combination( int, int ); int Combination(int n, int r) { int comb = Permutation(n,r); for (int i=1; i<=r; i++) comb /= i; return comb; Function Arguments float demo1(float x); passes x by value that is, changes to x in demo1 will not be seen by the calling program. Demo call: a = demo1(b+c); a = demo1(x); 2 31 Function Example Objective : Returns n! / (r!(n-r)!) Prototype : int Combination( int, int ); int Combination(int n, int r) { return nfact(n)/(nfact(r)*nfact(n-r)); Function Arguments Each argument must be individually typed, e.g., int f1(int a, int b);// correct int f2(int a, b); // incorrect Demo call: e = f1(f, g+h); Functions can have default argument values. int demo6(int n=0, int m=1); which means demo6(2) is the same as demo6(2,1) and demo6() is the same as demo6(0,1). 30 32 8

Function Arguments More than one function can have the same name (but different types of arguments). This is called function overloading. double cube(double x); long cube(long x); In this example, cube(2.5) will call the first function and cube() will call the second. C++ compares the type of value passed to a function and if different than the expected type, converts the argument to the correct type (if possible) 33