1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.

Slides:



Advertisements
Similar presentations
1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
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.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Chapter 6: User-Defined Functions I
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6: User-Defined Functions I
Chapter 6: Functions.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Function. Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Chapter 7 Functions CS185/09 - Introduction to Programming Caldwell College.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
1 CS161 Introduction to Computer Science Topic #9.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
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)
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 9: Value-Returning Functions
Chapter 6: User-Defined Functions I
Function Topic 4.
Chapter 5 Function Basics
CSC113: Computer Programming (Theory = 03, Lab = 01)
User-Defined Functions
Chapter 4: Subprograms Functions for Problem Solving
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 Function Basics
Chapter 6: User-Defined Functions I
Lesson #6 Modular Programming and Functions.
Functions Imran Rashid CTO at ManiWeber Technologies.
Eizan Aziz CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING
CPS125.
Presentation transcript:

1 FUNCTIONS - I Chapter 5

2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and hence are more manageable These sub programs are called functions They can be compiled and tested separately and reused in different programs

3 Things to do today… Functions Basics including… Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void Functions

4 Standard C++ Library As we have already seen, the Standard C++ library is a collection of pre-defined functions which are accessed through header files Notice about these pre-defined functions that the processing step is hidden : we do not need to know what the function does to produce the output

5 Example :The sqrt() function… This function returns the square root of a given positive number // sqroot.cpp #include using namespace std; int main() { int x; x = 2; cout << sqrt(9) << endl; cout << sqrt (10*x + 5) << endl; cout << sqrt(x) << endl; return 0; } Calls sqrt() Method 1, function call in a cout statement New library

6 Invoking a function, method 2 A function can be invoked or called in a cout statement as shown in the previous example or by assigning its value to a variable Example : float x=25, y; y=sqrt(x); cout<< x <<“ "<< y << endl; Method 2, function call in an assignment statement 25 5

7 Passing by value… What’s that ? Consider the function sqrt(x): The expression x is called the argument or actual parameter of the function call and we say that it is passed by value to the function So when x is 3, the actual value 3 is passed to the sqrt() function by the call sqrt(x)

8 This can be illustrated as : float x float y main() sqrt() Shaded box, Processing hidden

9 Check this out…!! Nesting of function calls … int main() { float y; y = sqrt(1 + 2*sqrt(3 + 4*sqrt(5))); cout<< y<< endl; }

10 abs(k) works with integers

11

12 Functions for processing char data (already included in namespace std) FunctionDescriptionExample isalnum(c) isalpha(c) isdigit(c) islower(c) isprint(c) ispunct(c) isupper(c) tolower(c) toupper(c) Tests if a char is alphanumeric Tests if a char is a letter Tests if a char is digit Tests for lowercase letter Tests for printable letter Tests for punctuation Tests for uppercase letter Takes upper case gives lower Takes lower case gives upper isalnum(‘x’) gives T isalpha(‘$’) gives F isdigit(‘3’) gives T islower(‘A’) gives F isprint(‘\n‘) gives F ispunct(‘!’) gives T isupper(‘A’) gives T tolower(‘G’) gives ‘g’ toupper(‘g’) gives ‘G’

13 Example use of char functions char ch; cin>>ch; if (islower(ch)) { cout << ch <<“ is lowercase letter” << endl; ch = toupper(ch); cout<<“Uppercase version is” <<ch<<endl; }

14 Random Number functions // random.cpp #include using namespace std; int main() { srand(time(NULL)); cout << rand()<< endl; //new random 0 - 2billion cout << rand()<< endl; //new random 0 - 2billion cout << rand()%10<< endl; // cout << rand()%6 + 1<< endl; // 1 – 6 dice roll return 0; } Has time function Seed random nums gen

15 Things to do today… Functions Basics including… Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void Functions

16 User-defined functions A user defined function has two parts : the head and the body Here is a simple example of a user defined function: float cube(float x) { return x*x*x; //returns cube of x }

17 User-defined functions.. Contd.. The syntax for the head of a function is : return-type name(parameter-list) In the given example the head of the function is: float cube(float x) return-type name(parameter-list) Another example: double dollar_value (int d, int q) // return value of dimes and quarters

18 The function body The body of a function is the block of code that follows its head It is written between the { } braces following the function header It contains the code that performs the function’s action Note that main() is a function whose body is the program itself

19 In the example… The function body is : { return x*x*x; //returns cube of x } This includes the return statement that specifies the value that the function sends back to the place where it was called

20 return… It terminates the execution of the function The function’s return-type specifies the data type of the values that it would return to the calling program Its syntax is : return expression ; where the data-type of the expression value = function's return-type

21 Things to do today… Functions Basics including… Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void Functions

22 Does my function work right ? That is the purpose of the test driver It is an ad-hoc program(minus all the usual niceties such as user prompts, output labels and documentation) written to test a function that we have created Remember the cube() function ? Let’s write a test driver for that…

23 float cube(float x) { // returns cube of x: return x*x*x; } int main() { // test driver for cube() function: cout<<"cube(1)= "<<cube(1)<<endl; cout<<"cube(-5)= "<<cube(-5)<<endl; cout<<"cube(4)= "<<cube(4)<<endl; }

24 Things to do today… Functions Basics including… Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void Functions

25 Two ways for defining functions The complete definition of the function is listed above the main program like : float cube(float x) { // returns cube of x: return x*x*x; } int main() { float n=5; cout<< cube(n) << endl; }

26 Another way is… List only the function’s header above the main program (declaration) like : float cube(float); (or) float cube(float x); List the function’s head and body below the main program (definition) declaration is also called a function prototype A function declaration is like a variable declaration

27 The previous program can also be written as : float cube(float x); //declaration int main() { float n=5; cout<< cube(n) << endl; } float cube(float x) //definition { // returns cube of x: return x*x*x; }

28 Actual Vs. Formal Parameters Actual parameters (We use ARGUMENTS) Parameters of the function in the function call Passed by value Formal parameters Variables listed in the function’s parameter-list in the function definition Local to that function The Arguments are copied to the Formal Parameters during function call

29 Actual Vs. Formal Parameters float cube(float); // function declaration int main() { float n=1; while (n > 0) { cin>> n; cout<<"cube("<< n <<") = "<< cube(n) <<endl; } // function definition float cube(float x) { // returns cube of x: return x*x*x; } Actual Parameter n Formal parameter x The value of n is copied into x for each function call

30 Things to do today… Functions Basics including… Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void Functions

31 Local variables and functions A local variable is declared inside a block and is accessible only from within that block Similarly a variable declared within a function is local to that function.. i.e it exists only when the function is executing A function’s formal parameters (used at that point where the function is actually defined) are also regarded as being local to the function

32 int max (int a, int b) { int larger; if (a > b) larger = a; else larger = b; return larger; } int main()//tests the max() function: { cout<<“max(5, 8) =”<<max(5,8)<<endl; cout<<“max(7, 3) =”<<max(7,3)<<endl; cout<<“max(7, 7) =”<<max(7,7)<<endl; } The variable larger is local to max…only can be used inside max Parameters a & b are like local variables too…only work inside max

33 In the last example The function has three local variables : a,b and larger The parameters a & b are local because it is declared in the function’s formal parameter list The parameter larger is local because it is declared within the body of the function

34 The max function could also be written without a local variable int max(int a, int b) { int larger; if (a > b) larger = a; else larger = b; return larger; } int max(int a, int b) { if (a > b) return a; else return b; } Both work the same way

35 What’s wrong with this ? float cube(float x) { // returns cube of x: return x*x*x; } int main() // tests the cube() function: {float n; cin>>n; while (n > 0) { x = cube(n); cout<<"cube(“ << n << ") = “ <<x<<endl; cin >> n; }

36 What’s wrong with this ? float cube(float x) { // returns cube of x: return x*x*x; } int main() { // test driver for cube() function: x = cube(1); cout<<"cube(1)= "<< x <<endl; cout<<"cube(-5)= "<<cube(-5)<<endl; cout<<"cube(4)= "<<cube(4)<<endl; }

37 This would work ! float cube(float x) { // returns cube of x: return x*x*x; } int main() { // test driver for cube() function: float x = cube(1); cout<<"cube(1)= "<< x <<endl; cout<<"cube(-5)= "<<cube(-5)<<endl; cout<<"cube(4)= "<<cube(4)<<endl; } But for now, try not to reuse variable names in functions

38 Data Types Must Match! char grade (double avg) { if (avg >= 92) return 'H'; else if (avg >= 65) return 'P' else return 'F'; } int main() { // test driver for grade(): float x = grade(95); cout<<“grade(95)= "<< x ; } What’s wrong here?

39 Data Types Must Match! char grade (double avg) { if (avg >= 92) return 'H'; else if (avg >= 65) return 'P' else return 'F'; } int main() { // test driver for grade(): char G = grade(95); cout<<“grade(95)= "<< G ; } Hint for Problem 10

40 Things to do today… Functions Basics including… Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void Functions

41 void Functions If a function does not return any value its return-type is void The void type specifies the empty set Think of an example for this type of function that does not return anything

42 This function does not return anything: void printhello(float x) { for (int i=0; i<x; i++) { cout<< "Hi There !!!!" << endl; } int main() { printhello(2); } Also Notice a void function call is just on a line by itself Don’t use in cout or assignment statements (like float functions) No return statement

43 And now for…. Global Variables-- A variable declared above/outside all functions Can be accessed by everyone Generally not a good idea for beginners Global Constants— A variable declared above/outside all functions Can be accessed by everyone Works great for things like PI that you use often

44 Summarizing what we did today.. Standard C++ library functions User - defined functions Test Drivers Function Declarations and Definitions Local variables and Functions void functions