Function. Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Chapter 5 Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
 2003 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
Function Introduction
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
1 Lecture 3 Part 1 Functions with math and randomness.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Main Objectives: To understand how to construct programs modularly from.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Introduction Program Components in C++ Math Library Functions Functions.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions.
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Dr. Shady Yehia Elmashad
IS Program Design and Software Tools Introduction to C++ Programming
FUNCTIONS IN C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Dr. Shady Yehia Elmashad
Chapter 3 - Functions Outline 3.1 Introduction
Functions Najah Alsubaie Kingdom of Saudi Arabia
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Dr. Shady Yehia Elmashad
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 6: User-Defined Functions I
Variables have attributes
Presentation transcript:

Function

Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function

Why do we need function?  Reuse and simplify a large program. Chapter 7 and Chapter 8 (p309-p436) Introduction Introduction

Library function Library function 1 // using library function. 2 #include 3 #include 4 5 using namespace std;; 6 7 int main() 8 { 9 cout << setw(4) <<123 << endl; return 0; // indicates successful termination } // end main

Include the header file Functions called by writing  setw (4); 4 can be replaced by  Constants: setw( 5 );  Variables: X=4; setw(x);  Expressions: X=2; setw( 6-x ); 9 int x=4; 10 cout << setw(x) <<123 << endl; 9 int x=2; 10 cout << setw(6-x) <<123 << endl; 10 cout << setw(5) <<123 << endl;

Math library function  Perform common mathematical calculations  Include the header file  Example cout << sqrt( ); sqrt (square root) function The preceding statement would print 30

1 // using math library function. 2 #include 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 // loop 10 times and calculate and output 11 // square root of x each time 12 for ( int x = -5; x <= 5; x++ ) 13 cout << abs (x) << “, "; // function call cout << endl; return 0; // indicates successful termination 18 } // end main Parentheses () cause function to be called. When the call done, the function result will be provided. Head file. 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,

1 // using math library function. 2 #include 3 // do not need any other header file. 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 // loop 10 times and calculate and output 11 // square root of x each time 12 for ( int x = -5; x <= 5; x++ ) { 13 If ( x <0) cout << -x << “, "; // if else, implementation of abs (x) 14 else cout << x << “, "; 15 } 16 cout << endl; return 0; // indicates successful termination 19 } // end main Without function call, the program needs implementation of abs here. 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,

Thinking? In program 1: Does the function know when it will be called? Is that function reused 11 times in the loop? (Does the name abs appear 11 times?) Do you care how to get absolute number in main? Comparing with a main program providing a detailed implementation of abs inside that loop, is this main more simple and easier to develop? No Yes No Yes 12 for ( int x = -5; x <= 5; x++ ) { 13 If ( x <0) cout << -x << “, "; 14 else cout << x << “, "; 15 } 12 for ( int x = -5; x <= 5; x++ ) 13 cout << abs (x) << “, "; Program 1Program 2

New defined function New defined function 3 aspects  Function prototype  Function call  Function definition Argument and parameter Pre-condition and post-condition Reference parameter Return value How to solve real problems by using arguments and parameters.

3 aspects 3 aspects Function prototype  Is used by compiler to check if the function call matches the function definition.  A simple sample: void function-name( ); Calling/invoking a function (function call)  A simple call: function-name();  Parentheses are used to call function (Control goes to function).  When the call done, the program will return to the point from which the function was called (Control goes back to caller).

3 aspects 3 aspects Function definition  A simple function definition void function-name() { statements } Simple sample Function heading, without “;”.

****************************** Welcome! ******************************

3 aspects 3 aspects Function definition  A simple function definition void function-name () { declarations and statements } 1 // using new defined function. 2 #include 3 using namespace std; 4 void print_star_one_line ( ); 5 6 int main() 7 { 8 print_star_one_line ( ); // print one line of stars. 9 print_star_one_line ( ); // another line 10 cout <<“Welcome!“<<endl; 11 print_star_one_line ( ); // print two lines of stars. 12 print_star_one_line ( ); return 0; // indicates successful termination 15 } // end main void print_star_one_line ( ) 18 { 19 cout << “******************************“<< endl; 20 } // end of function Parentheses () cause function to be called in main(). When the function done, the program will do the next statement. Function prototype.Function definition. Its statements inside will be executed when the function is called.

A function cannot be defined in other function such like: 17 void print_star_one_line ( ) 18 { 19 void print_one_star ( ) 20 { 21cout << ”*” << end; 22 } // end of function print_one_star } // end of function print_star_one_line

****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ****************************** Thinking? Do we need two different functions?

Argument and parameter Argument and parameter Make function more general by input parameter. With parameter in the function definition, function call with different value of argument can fulfill similar tasks. Argument:  A variable or expression listed in a function call;  Also called actual argument or actual parameter. Parameter:  A variable declared in a function heading;  Also called formal argument or formal parameter.

Argument and parameter Argument and parameter Example.  Express the following procedure: Two numbers; add them together; divide by 2. Try 9 and 8 Try 7 and 4  Did you use (x+y)/2 when you want to express the procedure?  Did you use (a+b)/2 when you want to express the procedure?

1 // using list of arguments and parameters, argument promotion. 2 #include 3 using namespace std; 4 void showavg ( int, int ); 5 6 int main() 7 { 8 showavg (9, 8); 9 showavg (7, 4); 10 return 0; //successful termination 11 } // end main void showavg (int num1, int num2) 14 { 15 cout << float(num1 + num2)/2 <<endl; 16 } // end of function We tried 9 and 8.We tried 7 and 4Instead of x and y (or a and b), I used num1 and num2.

Argument and parameter Argument and parameter General format (Prototype, Call, and Definition)  Function prototype Tells compiler argument type. void function-name( Datatype );  Function call function-name( argument ); An argument is passed to parameter in function definition  Function definition void function-name( DataType VariableName ) { statements // use VariableName; its value = value of the argument. }

1 // using argument and parameter. 2 #include 3 using namespace std; 4 void print_one_line ( char ); 5 6 int main() 7 { 8 print_one_line (‘*’ ); // print one line of stars. 9 print_one_line (‘A’ ); // print one line of ‘A’s. 10 cout <<“Welcome!“<<endl; 11 print_one_line (‘A’ ); // print another line of ‘A’s. 12 print_one_line (‘*’ ); // print another line of stars return 0; // indicates successful termination 15 } // end main void print_one_line ( char ch ) 18 { 19 Int i; 20 for ( int x = 1; x <= 30; x++ ) 21 cout << ch; 22 cout << endl; 23 } // end of function ‘*’ is passed to parameter. Use parameter ch as a variable. Its value comes from the argument. ch mainPrint_one_line ‘*’ ch ‘A’ Sequence Diagram

****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ******************************

Argument and parameter Argument and parameter The value of argument and parameter  Arguments can be constants, variables, and expressions  The argument will be evaluated to match the parameter when the function is called. Force arguments to be of definition type cout << sqrt(4) //Converting 4 to double (4.0)  The value will be passed to parameter.  The parameter is a variable and its value is according to the argument in different call.

1 // using argument and parameter. 2 #include 3 using namespace std; 4 void print_one_line (char ); 5 6 int main() 7 { 8 char c=’A’; 9 print_one_line (‘*’ ); // one line ‘*’. 10 print_one_line (c ); // one line ‘A’. 11 cout <<“Welcome!“<<endl; 12 print_one_line (c+ ’d’- ’c’ ); //one line ‘B’. 13 print_one_line (‘*’ ); // print another line of ‘*’. 14 return 0; // indicates successful termination 15 } // end main void print_one_line ( char ch ) 18 { 19 int i; 20 for ( int x = 1; x <= 30; x++ ) 21 cout << ch; 22 cout << endl; 23 } // end of function Constants, ‘*’ is passed to parameter, one line ‘*’. Variable, its value ‘A’ is passed to parameter, one line ‘A’. Expression, its value ‘B’ is evaluated and passed to parameter, one line ‘B’.

ch mainPrint_one_line ‘*’ ch ‘A’ Sequence Diagram ch ‘B’ constant value value of variable c value of expression

****************************** AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB ******************************

Argument and parameter Argument and parameter Advanced format (Prototype, Call, and Definition for multiple arguments and parameters)  Function prototype void function-name( DataTypeList ); The name of the function followed by data types of arguments. Comma separated list.  Function call function-name( ArgumentList ); The arguments are passed to the parameters according to their positions, left to right. Comma separated list of arguments.

Argument and parameter Argument and parameter Advanced format (Prototype, Call, and Definition)  Function definition void function-name( ParameterList ) { statements } If the list is present, it has the following form: DataType Parameter1, DataType Parameter2, … Comma separated list.

1 // using list of arguments and parameters, argument promotion. 2 #include 3 using namespace std; 4 void showavg ( int, int ); 5 6 int main() 7 { 8 char c=’a’; 9 int i=9, j=2; 10 showavg (i, j); 11 showavg (i, 2.5); 12 showavg (c*300, 11); 13 return 0; //successful termination 14 } // end main void showavg (int num1, int num2) 17 { 18 cout << float(num1 + num2)/2 <<endl; 19 } // end of function Argument List. The value of i and j, 9 and 2, are passed to num1 and num2. Datatype List The value of 2.5 (float) will be truncated to 2 and be passed to num2 (int). Parameter List. The type of c*300 will be promoted to int because it’s char * int.

Real Case ( Real Case ( A company and its delivery) Thinking?  For a guy who delivers the product of that company: Does he know what his job is? (function definition) Does he know what he will deliver? (parameter)  For the company: Does the company knows what the guy will deliver? (argument) Does the company care how he will deliver? (Does the main include the implementation of its functions?) Does the company need confirm the delivery? (Control goes back to main or caller when the function is done.) Company Guy of delivery service Product = ‘*’ His job is to handle (deliver) this ٱ. Control goes back (delivery confirmation). ‘*’ Call delivery service

Pre-condition and post-condition Pre-condition and post-condition Pre-condition:  To ensure there is no misuse.  An assertion that must be true before the function call  It may include: The acceptable range of argument The external resources the function used and their status. Post-condition:  To ensure the expecting result.  An assertion that should be true after the function is called.  It may include: The results All the external things this execution can change.

1 // Function void showavg (int, int). 2 // Pre-condition: 3 // Argument: two integer numbers 4 // external resource: None 5 // Post-condition: 6 // result: show the average on screen 7 // external thing changed: Only the monitor. 8 9 void showavg (int num1, int num2) 10 { 11 cout << float(num1 + num2)/2 <<endl; 12 } // end of function

void my_function ( ); //function prototype int main( ) { my_function( ); //function call return 0; } void my_function ( ) //function definition { } int k int x int k=3, m =4 ;, int, m, int y

Reference parameter Reference parameter Value parameter  A parameter that receives a copy of the value of the corresponding argument.  The change of value of this parameter variable in the function won’t change any thing in its caller (main).

ch mainfunction ‘*’ ch ‘A’ Sequence Diagram ch ‘B’ constant value value of variable c value of expression ‘*’ ‘A’ ‘B’ 1 // using argument and parameter. 2 #include 3 using namespace std; 4 void print_one_line (char ); 5 6 int main() 7 { 8 char c=’A’; 9 print_one_line (‘*’ ); 10 print_one_line (c ); 11 cout <<“Welcome!“<<endl; 12 print_one_line (c+ ’d’- ’c’ ); 13 print_one_line (‘*’ ); 14 return 0; 15 } // end main void print_one_line ( char ch ) 18 { 19 int i; 20 for ( int x = 1; x <= 30; x++ ) 21 cout << ch; 22 cout << endl; 23 } // end of function

Reference parameter Reference parameter A parameter that receives the location of the caller’s argument (main). The change of value of this parameter variable in the function will bring the change to main after the function call. The argument of its function call should be a variable (declared in main). General format: void function-name( Datatype & ); //prototype function-name( ArgumentVariable ); //call void function-name( DataType & VariableName ) // definition

ch, i mainFunction (char & ch) ‘*’ ch = ‘A’; Sequence Diagram variable i Function ( i ) ‘*’ ‘A’

1 // using reference parameter. 2 #include 3 using namespace std; 4 void showavg ( int, int, float & ); 5 int main() 6 { 7 float cf=1.2; 8 int i=9, j=2; 9 showavg (i, j,cf); 10 cout <<i << endl << cf <<endl 11 return 0; //successful termination 12 } // end main void showavg (int num1, int num2, float & avg) 15 { 16 avg = float(num1 + num2)/2; 17 num1 = 2; 18 } // end of function A variable in main. It will be used as reference argument. Datatype & Function call. No & here. The change of value of reference parameter. This change in function is brought to main by reference parameter. The change of value of value parameter won’t change the value of the argument variable i in main.

num1 main showavg 9 2 num2 Sequence Diagram avg, cf cf num1num2avg, cf cf 5.5 ij 9 2 ij

Return Return Return results by using reference parameters Return result by using return statement in function  Function prototype Tells compiler return type int square( int ); Function takes an int and returns an int  Function call cout << square(x) ; After finished, passes back result

Return Return Return result by using return statement in function  Function definition return-value-type function-name ( parameter-list ) { statements return Result; } Return-value-type: Data type of result returned (use void if nothing returned) The value of Result will be evaluated and passed back to caller (main). If no data to return (void), use return;

1 2 // using return statement. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int square( int ); // function prototype 9 10 int main() 11 { 12 // loop 10 times and calculate and output 13 // square of x each time 14 for ( int x = 2; x <= 10; x++ ) 15 cout << square( x ) << " "; // function call cout << endl; return 0; // indicates successful termination } // end main 22 Parentheses () cause function to be called. When done, it returns the result. Function prototype: specifies data types of arguments and return values. square expects int, and returns an int.

23 // square function definition returns square of an integer 24 int square( int y ) // y is a copy of argument to function 25 { 26 return y * y; // returns square of y as an int } // end function square Definition of square. Returns y * y, or y squared.

1 2 // using reference parameters for several return values. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 void square_and_root( int, int&, float& ); // function prototype 9 10 int main() 11 { 12 int s; 13 float r; 14 for ( int x = 2; x <= 5; x++ ) { 15 square_and_root( x, s, r ) ; // function call 16 cout << s << “, " << r << “; "; // show two results 17 } 18 cout << endl; 19 return 0; // indicates successful termination } // end main 22 Parentheses () cause function to be called. When done, it returns two results in variables s and r. Function prototype: specifies data types of arguments and return values. Square_and_root expects an int, and returns two results in reference parameters int & and float &.

23 // function definition returns square and square root 24 void square_and_root( int x, int &y, float & z ) 25 { 26 y = x* x; // returns square of x as an int 27 z = sqrt(x); // returns square root of x as an float 28 } // end function square 4, ; 9, ; 16, 2; 25, ; Definition of square. Returns the change of y and z to main by using reference parameter.

24 int square( int y ) 25 { 26 return y * y; } 24 void square_and_root( int x, int &y, float & z ) 25 { 26 y = x* x; 27 z = sqrt(x); 28 } The function using return statement is easy to read and can return one value to its caller. The function using reference parameter has a long list of parameters. has a complicated execution. can return more values. Exercises

1 #include 2 using namespace std; int main() 6 { 7 for ( int x = 1; x <= 30; x++ ) 8 cout << ”*”; 9 cout << endl; 10 for ( int x = 1; x <= 30; x++ ) 11 cout << ”*”; 12 cout << endl; 13 cout <<“Welcome!“<<endl; 14 for ( int x = 1; x <= 30; x++ ) 15 cout << ”*”; 16 cout << endl; 17 for ( int x = 1; x <= 30; x++ ) 18 cout << ”*”; 19 cout << endl; return 0; 22 } 1 #include 2 using namespace std; 3 void print_one_line ( ); 4 5 int main() 6 { 7 print_one_line ( ); 8 print_one_line ( ); 9 cout <<“Welcome!“<<endl; 10 print_one_line ( ); 11 print_one_line ( ); 12 return 0; 13 } // end main void print_one_line ( ) // function heading 16 { // function body 17 for ( int x = 1; x <= 30; x++ ) 18 cout << ”*”; 19 cout << endl; 20 } // end of function Function prototype Function call Function definition ****************************** Welcome! ******************************

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Welcome! BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB ****************************** 1 // using argument and parameter. 2 #include 3 using namespace std; 4 void print_one_line (char ); 5 6 int main() 7 { 8 char c=’A’; 9 print_one_line (‘*’ ); 10 print_one_line (c ); 11 cout <<“Welcome!“<<endl; 12 print_one_line (c+ ’d’- ’c’ ); 13 print_one_line (‘*’ ); 14 return 0; 15 } // end main void print_one_line ( char ch ) 18 { 19 for ( int x = 1; x <= 30; x++ ) 20 cout << ch; 21 cout << endl; 22 } // end of function Type of argument Argument Parameter

Question on page 19: Get the average of two numbers Two factors: (x+y) /2 (or (a+b)/2) Two arguments Two parameter variables How to solve real problems by using arguments and parameters

1 //using multiple arguments and parameters. 2 #include 3 using namespace std; 4 void showavg ( int, int ); 5 6 int main() 7 { 8 showavg (9, 8); 9 showavg (7, 4); 10 return 0; //successful termination 11 } // end main void showavg (int num1, int num2) 14 { 15 cout << float(num1 + num2)/2 <<endl; 16 } // end of function The average number is printed out when the function is called every time. How can the caller use the result of function?

1 // using return statement. 2 #include 3 using namespace std; 4 float get_avg ( int, int ); 5 6 int main() 7 { 8 cout << get_avg (9, 8) <<endl; 9 cout << get_avg (7, 4) <<endl; 10 return 0; //successful termination 11 } // end main float get_avg (int num1, int num2) 14 { 15 return float(num1 + num2)/2; 16 } // end of function Do we need return?  Program using return statement Return statementReturn type

1 // using return statement. 2 #include 3 using namespace std; 4 void get_avg ( int, int, float & ); 5 6 int main() 7 { 8 int r; 9 get_avg (9, 8, r ); 10 cout << r <<endl; 11 get_avg (7, 4, r ); 12 cout << r <<endl; 13 return 0; //successful termination 14 } // end main void get_avg (int num1, int num2, float & res) 17 { 18 res = float(num1 + num2)/2; 19 } // end of function  Program using reference parameter Reference parameter

 Solution for exercises Get the larger one of two numbers Two factors Two arguments Two parameter variables

1 // using return statement. 2 #include 3 using namespace std; 4 int get_larger ( int, int ); 5 6 int main() 7 { 8 int x, y; 9 cin >> x >> y; 10 cout << get_larger (x, y) <<endl; //function call 11 return 0; //successful termination 12 } // end main int get_larger (int num1, int num2) 15 { 16 if (num1 > num2) 17 return num1; 18 else return num2; 19 } // end of function “cout function with return statement

1 // using return statement. 2 #include 3 using namespace std; 4 int get_larger ( int, int ); 5 6 int main() 7 { 8 int x, y; 9 cin >> x >> y; 10 cout << get_larger (x, y) <<endl; 11 return 0; //successful termination 12 } // end main int get_larger (int num1, int num2) 15 { 16 return (num1 > num2)? num1: num2; 17 } // end of function

1 // using reference parameter. 2 #include 3 using namespace std; 4 void get_larger ( int, int, int & ); 5 6 int main() 7 { 8 int x, y, larger; 9 cin >> x >> y; 10 get_larger (x, y, larger ); 11 cout << larger <<endl; 12 return 0; //successful termination 13 } // end main void get_avg (int num1, int num2, int & res) 16 { 17 res = (num1 > num2)? num1: num2; 18 } // end of function “cout <<larger;” -> function with reference parameter “larger”.

Usage Format Example Random number generator Random number generator

Random selection  rolling dice, and etc. rand function ( )  i = rand();  Generates unsigned integer between 0 and RAND_MAX (usually 32767)  Generates integer between a and b. i = rand() % 6 + 1; “Rand() % 6” generates a number between 0 and 5 (scaling) x % y is between 0 and y – 1, i.e., 10 % 3 is 1 “+ 1” makes the range 1 to 6 (shift) Example: Program to roll dice.

1 // Shifted, scaled integers produced by 1 + rand() % 6. 2 #include 3 #include 4 #include // contains function prototype for rand 5 6 using namespace std; 7 8 int main() 9 { 10 // loop 20 times 11 for ( int counter = 1; counter <= 20; counter++ ) { // pick random number from 1 to 6 and output it 14 cout << setw( 10 ) << ( 1 + rand() % 6 ); 15 // if counter divisible by 5, begin new line of output 16 if ( counter % 5 == 0 ) 17 cout << endl; } // end for structure return 0; // indicates successful termination 22 } // end main Output of rand() scaled and shifted to be a number between 1 and 6. Head file.

Thinking Is this fair?

1 // Roll a six-sided die 6000 times. 2 #include 3 #include 4 #include // contains function prototype for rand 5 6 using namespace std; 7 8 int main() 9 { 10 int frequency1 = 0; 11 int frequency2 = 0; 12 int frequency3 = 0; 13 int frequency4 = 0; 14 int frequency5 = 0; 15 int frequency6 = 0; 16 int face; // represents one roll of the die 17

18 // loop 6000 times and summarize results 19 for ( int roll = 1; roll <= 6000; roll++ ) { 20 face = 1 + rand() % 6; // random number from 1 to // determine face value and increment appropriate counter 23 switch ( face ) { 24 case 1: // rolled frequency1; 26 break; 27 case 2: // rolled frequency2; 29 break; 30 case 3: // rolled frequency3; 32 break; 33 case 4: // rolled frequency4; 35 break; 36 case 5: // rolled frequency5; 38 break;

39 case 6: // rolled frequency6; 41 break; 42 default: // invalid value 43 cout << "Program should never get here!"; } // end switch } // end for // display results in tabular format 50 cout << "Face" << setw( 13 ) << "Frequency" 51 << "\n 1" << setw( 13 ) << frequency1 52 << "\n 2" << setw( 13 ) << frequency2 53 << "\n 3" << setw( 13 ) << frequency3 54 << "\n 4" << setw( 13 ) << frequency4 55 << "\n 5" << setw( 13 ) << frequency5 56 << "\n 6" << setw( 13 ) << frequency6 << endl; return 0; // indicates successful termination } // end main Default case included even though it should never be reached. This is a matter of good coding style

Face Frequency

Calling rand() repeatedly  Gives the same sequence of numbers  To get different random sequences Provide a seed value Like a random starting point in the sequence The same seed will give the same sequence srand(seed); Used before rand() to set the seed

1 // Randomizing die-rolling program. 2 #include 3 #include 4 #include 5 using namespace std; 6 7 int main() 8 { 9 unsigned seed; cout << "Enter seed: "; 12 cin >> seed; 13 srand( seed ); // seed random number generator 14 // loop 10 times 15 for ( int counter = 1; counter <= 10; counter++ ) { 16 // pick random number from 1 to 6 and output it 17 cout << setw( 10 ) << ( 1 + rand() % 6 ); 18 // if counter divisible by 5, begin new line of output 19 if ( counter % 5 == 0 ) 20 cout << endl; 21 } // end for 22 return 0; // indicates successful termination 23 } // end main Setting the seed with srand() before rand().

Enter seed: Enter seed: Enter seed: rand() gives the same sequence if it has the same initial seed.

 Can use the current time to set the seed Use current time as seed srand( time( 0 ) ); time( 0 ); Returns current time in seconds Number = shiftingValue + rand() % scalingFactor shiftingValue = first number in desired range scalingFactor = width of desired range

1 // Shifted, scaled integers produced by 1 + rand() % 6. 2 #include 3 #include 4 #include // contains function prototype for rand 5 #include // contains function prototype for time 6 using namespace std; 7 8 int main() 9 { 10 srand ( time( 0 )); 11 for ( int counter = 1; counter <= 20; counter++ ) { // pick random number from 1 to 6 and output it 14 cout << setw( 10 ) << ( 1 + rand() % 6 ); 15 // if counter divisible by 5, begin new line of output 16 if ( counter % 5 == 0 ) 17 cout << endl; } // end for structure return 0; // indicates successful termination 22 } // end main Use current time as seed.

Introduction Local scope Global scope Name precedence Static variable Scope Scope

num1 main showavg 9 2 cf 1. 2 cf 5.5 i j avg Lifetime num2 5.5 Introduction (Lifetime) Introduction (Lifetime) int main() 6 { 7 float cf=1.2; 8 int i=9, j=2; 9 showavg (i, j,cf); 10 cout <<i << endl << cf <<endl 11 return 0; //successful termination 12 } // end main void showavg (int num1, int num2, float & avg) 15 { 16 avg = float(num1 + num2)/2; 17 num1 = 2; 18 } // end of function

Introduction (scope) Introduction (scope) Scope  Portion of program where identifier can be used. Local scope Global scope

Local scope Local scope Local variables, function parameters Scope begins at declaration, ends at right brace Variable created when program enters its block Variable invalid when program leaves block Variable destroyed when program reaches the right brace of this block

1 // using arguments and parameters. 2 #include 3 using namespace std; 4 void showavg ( int, int, float & ); 5 int main() 6 { 7 float cf=1.2; 8 int j; 9 for ( j = 1; j <= 5; j++ ) { 10 int i = 9; 11 showavg( i, j, cf ) ; // function call 12 cout <<i << endl << cf <<endl 13 } 14 return 0; //successful termination 15 } // end main void showavg (int num1, int num2, float & avg) 18 { 19 avg = float(num1 + num2)/2; 20 } // end of function num1 i Local scope starts from declarationLocal variable will be invalid when the program leaves main for showavg. Create a new block, giving i block scope. When the block ends (the program reaches the right brace of the block), this i is destroyed.

{ ………… int i; i=i+1; ………… } { int i; ………… i=i+1; ………… } int i; i = i+2;

Global scope Global scope Global variables (constants), function definitions and prototypes Defined outside of any function in a file Scope begins at declaration, ends at the end of this file Variable created when program starts Variable is valid from its declaration to the end of this file. Variable destroyed when program ends

1 // using global variables. 2 #include 3 using namespace std; 4 5 double c_area( int ); 6 const double pi = 3.14; 7 8 int main() 9 { 10 cout << “When pi is " << pi <<endl; for ( int x = 1; x <= 10; x++ ) 13 cout << c_area( x ) << " "; 14 cout << endl; 15 return 0; 16 } // end main double c_area( int radius) 19 { 20 return radius * radius * pi; 21 } // end function square 1 // using global variables. 2 #include 3 using namespace std; 4 5 const double pi = 3.14; 6 7 double c_area( int radius) 8 { 9 return radius * radius * pi; 10 } // end function square int main() 13 { 14 cout << “When pi is " << pi <<endl; for ( int x = 1; x <= 10; x++ ) 17 cout << c_area( x ) << " "; 18 cout << endl; 19 return 0; 20 } // end main 21

Thinking - End of local End of file block No Yes

Name precedence Name precedence When a function declares a local identifier with the same name as a global identifier, the local identifier takes precedence within the function. The precedence that a local identifier in a function has over a global identifier with the same name in any references that the function makes to that identifier; also called name hiding.

1 // using name precedence. 2 #include 3 using namespace std; 4 5 double c_area( int ); 6 const double pi = 3.14; 7 8 int main() 9 { 10 cout << “When pi is " << pi <<endl; cout << c_area(10 ) << " "; 14 cout << endl; 15 return 0; 16 } // end main double c_area( int radius) 19 { 20 int pi = 3; 20 return radius * radius * pi; 21 } // end function square pi 3.14 pi 3 main c_area

When pi is

Static variable Static variable Variables exist for entire program Static local variables in function  Keeps value between function calls  Variable created once when program first entered the function  Only known in own function  Variable destroyed when program ends

1 // using local static. 2 #include 3 using namespace std; 4 void useStaticLocal( ) 5 6 int main() 7 { 8 for ( int x = 1; x <= 10; x++ ) 9 useLocal( ); 10 return 0; 11 } // end main void useLocal ( ) 14 { 15 // initialized only first time useStaticLocal is called 16 int y = 50; cout << "local x is " << y ++ << endl; 19 } // end function useStaticLocal Local variable of function; it is initialized every time when the program call this function. Y=50 main useLocal 51 Y=50 useLocal 51 Y=50 useLocal 51 …

local x is 50

1 // using local static. 2 #include 3 using namespace std; 4 void useStaticLocal( ) 5 6 int main() 7 { 8 for ( int x = 1; x <= 10; x++ ) 9 useStaticLocal( ); 10 return 0; 11 } // end main void useStaticLocal ( ) 14 { 15 // initialized only first time useStaticLocal is called 16 static int y = 50; cout << "local static x is " << y ++ << endl; 19 } // end function useStaticLocal Static local variable of function; it is initialized only once, and retains its value between function calls. Y=50 main useStaticLocal 51 useStaticLocal 52 useStaticLocal 53 …

local static x is 50 local static x is 51 local static x is 52 local static x is 53 local static x is 54 local static x is 55 local static x is 56 local static x is 57 local static x is 58 local static x is 59

Inline function Inline function Inline functions  Keyword inline before function  Asks the compiler to copy code into program instead of making function call Reduce function-call overhead Compiler can ignore inline  Good for small, often-used functions Example inline double cube( const double s ) { return s * s * s; }  const tells compiler that function does not modify s

1 // Using an inline function to calculate. 2 #include 3 using namespace std; 4 5 // Definition of inline function cube. Definition of function 6 // appears before function is called, so a function prototype 7 // is not required. First line of function definition acts as 8 // the prototype. 9 inline double cube( const double side ) 10 { 11 return side * side * side; // calculate cube 12 } // end function cube int main() 15 { 16 double sideValue; 17 cout << "Enter the side length of your cube: "; 18 cin >> sideValue; 19 // calculate cube of sideValue and display result 20 cout << "Volume of cube with side " 21 << sideValue << " is " << cube( sideValue ) << endl; 22 return 0; // indicates successful termination 23 } // end main

Enter the side length of your cube: 3.5 Volume of cube with side 3.5 is

Function overloading Function overloading Function overloading  Functions with same name and different parameters  More general, should perform similar tasks I.e., function to square int s and function to square float s int square( int x) {return x * x;} float square(float x) { return x * x; } Overloaded functions distinguished by signature  Based on name and parameter types (order matters)

1 // Using function overloading to calculate. 2 #include 3 using namespace std; 4 5 inline double square ( const double side ) 6 { 7 cout << “double “; 8 return side * side; // calculate double square 9 } // end function square inline int square ( const int side ) 12 { 13 cout << “integer “; 14 return side * side; // calculate int square 15 } // end function square int main() 18 { 19 // calculate squre of sideValue and display result 20 cout << “Square with side 2 is " << square( 2 ) << endl; 21 cout << “Square with side 3.2 is " << square( 3.2 ) << endl; 22 return 0; // indicates successful termination 23 } // end main The proper function is called based upon the argument (int or double).

Square with side 2 is integer 4 Square with side 3.2 is double 10.24

1 // Fig. 3.4: fig03_04.cpp 2 // Finding the maximum of three floating-point numbers. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 double maximum( double, double, double ); // function prototype int main() 12 { 13 double number1; 14 double number2; 15 double number3; cout << "Enter three floating-point numbers: "; 18 cin >> number1 >> number2 >> number3; // number1, number2 and number3 are arguments to 21 // the maximum function call 22 cout << "Maximum is: " 23 << maximum( number1, number2, number3 ) << endl; return 0; // indicates successful termination Function maximum takes 3 arguments (all double ) and returns a double.

26 27 } // end main // function maximum definition; 30 // x, y and z are parameters 31 double maximum( double x, double y, double z ) 32 { 33 double max = x; // assume x is largest if ( y > max ) // if y is larger, 36 max = y; // assign y to max if ( z > max ) // if z is larger, 39 max = z; // assign z to max return max; // max is largest value 42 } // end function maximum Enter three floating-point numbers: Maximum is: Enter three floating-point numbers: Maximum is: Enter three floating-point numbers: Maximum is: Comma separated list for multiple parameters.