Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 5 Functions.
Overview creating your own functions calling your own functions.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
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.
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)
CSE 1341 Honors Note Set 2 1. Overview  Java vs. C++  Functions in C++  First Programming Packet  Development Environment 2.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
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 Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
CS1201: Programming Language 2 Function I By: Nouf Aljaffan Edited by : Nouf Almunyif.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
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
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Chapter 5 Function Basics
FUNCTIONS IN C++.
Programming Fundamentals Lecture #7 Functions
CSC1201: Programming Language 2
User Defined Functions
Chapter 5 Function Basics
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
6 Chapter Functions.
Functions.
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Function “Inputs and Outputs”
Chapter 6: User-Defined Functions I
CSC1201: Programming Language 2
Function Defaults C++ permits functions to be declared with default values for some, or all, of its parameters Allows for the function to be called without.
CS150 Introduction to Computer Science 1
Fundamental Programming
CSC1201: Programming Language 2
Predefined Functions Revisited
Functions Imran Rashid CTO at ManiWeber Technologies.
Chapter 8 Functions.
CS1201: Programming Language 2
Chapter 1 c++ structure C++ Input / Output
CPS125.
Presentation transcript:

Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and debug the function once Avoid redundancy Procedural (top-down) approach design program, then fill in functions – “structured”

Sources of functions C++ (built-in) Shared libraries (open source, for ex.) Other developers on a team Write it yourself

Elements of a Function Functions include: A name A return type ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } Functions include: A name A return type “Input” parameters, including a type and a name As needed, internal statements If “output” is desired, a return statement

Function name and type Functions are “called”, or invoked by name ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } Functions are “called”, or invoked by name The return type of the function determines the data type of the value that the function will “return” as its output Can be any valid C++ data type (ex: int, float, …) or even a user- defined data type (like a struct) Use the keyword void, if no output is required

Function Parameters ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } Function parameters (also called formal parameters) Serve as “inputs” to the function (by default) Listed in parenthesis after the function name separated by commas For each parameter, include a type and a name Can have as many parameters as desired Each with its own type

Function Statements ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } The number and type of internal statements in a function are determined completely by the task the function performs The writer of the function has the freedom to declare variables and write statements as needed Any variables declared are “local” to the function

Function – return statement ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } The return statement of a function serves as its “output” It can be a variable or an expression The resulting value will be cast to the type of the function declaration, if it doesn’t already match that type No return statement is needed if the function type is declared as “void”

Function Examples string getName() { string name; float add(float x, float y) { float sum; sum= x + y; return sum; } void hello(string name) { cout << “Hello “ << name << endl; } string getName() { string name; cout << “Enter name: “; cin >> name; return name; }

Function Invocation Functions are called by Invoking the function name Providing a list of “inputs” Items in the list are called arguments The arguments much match the defined function parameters by number and type But not, necessarily, by name z= add(a,b); // where a, b, and z are declared as floats After this statement is executed, z will contain the sum of a and b (using “add()” as declared previously)

Example $ ./a.out Enter a number: 2 The square of 2 is 4 $ #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // compute the square, output it vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; $ ./a.out Enter a number: 2 The square of 2 is 4 $ vsqr gets assigned the return value of the function square

Local Variables and “Scope” All variables in a function are “local” to the function Including both parameters (in the “input” list) And variables declared in internal function statements They are created “on-the-fly” when the function is invoked They are destroyed when the function returns (finishes) They have local scope Any modifications to a local variable do not affect variables in the calling routine even if they have the same name!

“Pass by Value” Any variable used in the function’s “input” list as an argument during a function call has it’s value copied, or “passed”, to the parameter variable The parameter value, with its copied value, can then used in the function as a local variable Any changes to the parameter variable do NOT affect the original argument variable from the calling routine They are separate variables, even if they have the same name! Because function variables have local scope!

Steps in Program Execution Always begins in main() main() gets loaded on the “runtime stack” Statements on stack executed in order encountered When a function is encountered Code for the function is loaded on the runtime stack Values of the arguments are copied into the newly created parameter variables Code in runtime stack resumes execution (now in function code) Function code completes Return value copied to variable in main, if appropriate Function code removed from the stack, local variables and parameters are destroyed Runtime stack resumes execution of code in main() at the point after the function was called

Begin Execution main() num vsqr 2 ? Runtime Stack #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { return x*x; main() num vsqr 2 ? Runtime Stack main() gets loaded on the runtime stack User types “2”

Load Function Runtime Stack main() num vsqr 2 ? square() x sq #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 ? square() x sq square() gets loaded on the stack x and sq get created Value of num gets copied to x

Execute Function Runtime Stack main() num vsqr 2 ? square() x sq 4 #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 ? square() x sq 4 Code in square() gets executed Result (4) is stored locally in sq

Return Value Runtime Stack main() num vsqr 2 4 square() x sq #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 4 square() x sq “replaced” by “4” Result (4) is copied back, i.e. returned, to vsqr in main() from sq in square() Imagine that square(num) is “replaced” by the “return value”

Destroy function Runtime Stack main() num vsqr 2 4 #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 4 square(), and its local variables are removed from stack main() completes execution

Prototypes A prototype is a function “declaration” #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; A prototype is a function “declaration” C++ is a “strongly typed” language All variables and functions must be declared before use A prototype tells the compiler that function exists and its form

Rules for Prototypes float add(float, float); A prototype must contain The function name Its return type A list of parameter types Names of parameters are allowed but are not required float add(float, float); float add(float x, float y); Prototype must appear before first use of function Actual function definition can follow later Prototype not required if function definition occurs before use But common practice is to create prototypes

One more thing… Functions can be called using literals as arguments It is not necessary to use a variable in a function call add(x,y); add(x,3); add(2,y); add(2,3); Are all valid function calls (Unless the formal parameter is a reference variable…)