ITM 352 Functions.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
IS 1181 IS 118 Introduction to Development Tools Chapter 5 Reusing Code.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Functions & Objects IDIA 618 Spring 2012 Bridget M. Blodgett.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 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.
Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
 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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016.
User-Written Functions
Topics Introduction to Functions Defining and Calling a Void Function
Chapter 7 User-Defined Methods.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 3 OF 3
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
C Functions Pepper.
Functions, locals, parameters, and separate compilation
Variables, Expressions, and IO
Object Oriented Systems Lecture 03 Method
Function There are two types of Function User Defined Function
JavaScript: Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
User Defined Functions
Starting Out with Java: From Control Structures through Objects
Chapter 6 Methods: A Deeper Look
Chapter 4 void Functions
6 Chapter Functions.
PHP.
Object Oriented Programming in java
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Topics Introduction to Functions Defining and Calling a Void Function
Tonga Institute of Higher Education
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Topics Introduction to Functions Defining and Calling a Function
Suggested self-checks: Section 7.11 #1-11
COMPUTER PROGRAMMING SKILLS
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Programming Languages and Paradigms
Methods/Functions.
CPS125.
Corresponds with Chapter 5
Presentation transcript:

ITM 352 Functions

Functions A function is a named block of code (i.e. within {}'s) that performs a specific set of statements It acts on a set of values given to it (parameters) It may return a single value (return-value) Functions are very useful for Repeated tasks in multiple locations Sharing useful code Saving execution time Modularization: Dividing up the task

Functions We've already made use of several functions! Can you think of some? Some functions are built in to PHP, some are added from code libraries, some you will define

Calling a Function All PHP functions are designated by <identifier>(<parameters>) e.g. phpinfo(), rand(1,10) Function names are not case sensitive Full interface for a function: <return type> <identifier> ( <parameters> ) identifier parameters

Calling a Function Functions are used by calling them <?php … $commission = $sales * $rate; echo round($commission,2); ?> the "call"

Passing Values into a Function: Parameters Some Functions can be more flexible (therefore useful) if we pass them input values to use in their operations Input values for functions are called passed values or parameters Parameters must be specified inside the parentheses () of the function, and must be of the expected data type, in the expected order as defined by the function's interface rand(int min, int max) rand(1,10); Parameter 2: max (int) Parameter 1: min (int)

rand($minGuess,$maxGuess); Passing Variables Any legal expression can be used as a parameter (recall that an expression returns a value) rand(44%3, 2*$max*$max); It is very common to use a variable for a parameter (recall: a variable by itself is an expression – it returns the value of the variable) rand($minGuess,$maxGuess); substr($name,1,$i);

Return Values of Functions Some Functions just perform an action (e.g. read in a value from the keyboard, switch to a web page) and do not return a value Most functions perform an action and return a single value Return types may be: a primitive data type, such as int, float, boolean, etc. a compound type such as array, object, etc. void if no value is returned Return values are how a function passes information back after it is called and after it performs its operations.

Return Values of Functions You can use a function with a returned value any place where it is legal to use an expression, $guess = rand(1,10); 3.14159*rand(1,10); echo phpinfo(); $yummy = "piece of " . substr("piece",0,3); if( is_int($guess) ) … A common return value for a function is boolean true is the function operations were successful with no problems false if the function failed to perform its task if( !writeFile() ) echo "file not written";

Function Documentation Functions are documented not only with a description of the function, but also with a interface that shows the return value type, the name of the function, and the required and optional arguments: type function_name (type arg1, type arg2 [,type optional_arg]) PHP functions often document functions this way: printf (PHP 3, PHP 4 ) printf -- Output a formatted string Description void printf ( string format [, mixed args]) Outputs a string by using format and the given arguments … function name function signature function description

ITM 352 Creating Functions

Defining Functions A very important aspect of PHP is the ability to create your own functions. You will find out how useful this is later. You declare a function with the function keyword in front of a identifier and function parameter set and a code-block: function <identifier> ( <parameters> ) { // function operations (code statements) here return <expression> } The way you define a function defines the functions interface (or how it is expected to be used)

Function Syntax and Example function funcname($var1, $var 2...) { statement 1; statement 2; statement 3; ... return $retval; } function square($num) { $answer = $num * $num; return $answer; } To call the function: $quantity = 3; $myvar = square ($quantity); $myvar will contain the value 9 NOTE that the variable names do not need to be the same; the order of variables passed is what will matter inside the function!

Global vs. Local Variables Variables defined inside a function (or passed in) are "local variables" and are only available within functions after exiting the function the variable ceases to exist!!! Variables defined outside of a function are generally not available inside a function. So variables should be passed into a function as arguments!!! Global variables are accessible both in and out of functions NOT recommended!!! DO NOT DO IT!!!! Where the variable is active (alive) is known as its "scope" use global and static to modify this also "passing by reference" will affect scope

Scope of Variables Inside a function is like an entirely new program!!! Variables that you define within the function have "local" scope: They don't exist before the function starts They don't exist once the function has completed

What will this program print? Scope of Variables – 2 <?php function deposit($amount) { $balance = $balance + $amount; echo "New balance is $balance <BR>"; } $balance = 600; deposit(50); echo "Balance is $balance"; ?> What will this program print? Why?

What would happen if we used $a and $b instead? Defining Functions function swapTwoValues($a, $b) { $tmp = $a; // save old value temporarily $a = $b; // copy second parameter into first $b = $tmp; // copy original first value into second } $var1 = 1; $var2 = 2; echo "\$var1 is $var1 and \$var2 is $var2<BR>"; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2"; What would happen if we used $a and $b instead?

Function Naming Conventions Good Programming Practice (we will look for this!) Use verbs to name functions that do not return values or operate directly on variables They usually perform an action e.g. sort(), print_table() Use nouns to name functions that return a value they create (return) a piece of data, a thing e.g. date() Start function names with a lower case letter phpinfo() Use "_" to separate words is_bool() Use descriptive names get_html_translation_table()

Pass-By-Value vs. Pass-By-Reference When a function is called, the value of each argument is copied (assigned) and used locally within that function Variables used as arguments cannot be changed by a function!!!!!!!!! One way to change a value of a passed in variable is to make use of return value: function doubler($value) { return 2*$value; } echo doubler($doubleUp); $doubleUp = doubler($doubleUp);

Pass-By-Value vs. Pass-By-Reference Sometimes it's more convenient to directly operate on a variable, so you pass in its reference (address): function swapTwoValues(&$a, &$b) { $tmp = $a; // save old value temporarily $a = $b; // copy second parameter into first $b = $tmp; // copy original first value into second } $var1 = 1; $var2 = 2; echo "\$var1 is $var1 and \$var2 is $var2<BR>"; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2";