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.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Introduction to C Programming
1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
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.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
 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.
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
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 Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
Classes, Objects, and Methods
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.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
PHP Constructs Advance Database Management Systems Lab no.3.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
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.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
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.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
 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.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
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
Variables, Expressions, and IO
Object Oriented Systems Lecture 03 Method
Function There are two types of Function User Defined Function
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.
Classes, Objects, and Methods
PHP.
Chapter 6 – Methods Topics are:
1-6 Midterm Review.
Methods/Functions.
ITM 352 Functions.
CPS125.
Corresponds with Chapter 5
Presentation transcript:

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 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

ITM 3523 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 Do Lab #1

ITM 3524 Calling a Function  All PHP functions are designated by ( )  e.g. phpinfo(), rand(1,10)  Function names are not case sensitive  Full interface for a function:  ( ) identifier parameters

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

ITM 3526 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 1: min (int) Parameter 2: max (int)

ITM 3527 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); Do Lab #2

ITM 3528 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.

ITM 3529 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);  *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"; Do Lab #3

ITM 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 …  You can look up functions using the book index, Appendix A function categories, or PHPed's help function name function signature function description Do Lab #4

ITM ITM 352 Creating Functions

ITM 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 ( ) { // function operations (code statements) here return }  The way you define a function defines the functions interface (or how it is expected to be used)

ITM 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!

ITM 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!!! DON’T 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

ITM 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

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

ITM 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 "; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2"; What would happen if we used $a and $b instead?

ITM 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()

ITM 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);

ITM 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 "; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2"; Do Lab #5