37
CSCI 116 Week CSCI 116 Week 3 3 Functions & Functions & Control Control Structures Structures

CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

  • View
    227

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

CSCI 116 Week 3CSCI 116 Week 3

Functions & Functions & Control StructuresControl Structures

Page 2: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

22

TopicsTopics

Using functionsUsing functions Variable scope and autoglobalsVariable scope and autoglobals Decision logicDecision logic

• ifif statements statements• if...elseif...else statements statements• switchswitch statements statements

LoopsLoops• whilewhile statements statements• do...whiledo...while statements statements• forfor and and foreachforeach statements statements

Page 3: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

33

Defining FunctionsDefining Functions

Functions Functions • Groups of statements that you can Groups of statements that you can

execute as a single unitexecute as a single unit Defining a functionDefining a function::

<?php<?php

function function name_of_functionname_of_function((parametersparameters) )

{{

statementsstatements;;

}}

?>?>

Page 4: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

44

Function ParametersFunction Parameters A A parameterparameter is an input to the function is an input to the function Parameters are placed within the Parameters are placed within the

parentheses that follow the function parentheses that follow the function namename

Not all functions accept parametersNot all functions accept parameters

function average($num1, $num2)

function printHello()

function calcTax($price)

2 parameters2 parameters

0 parameters0 parameters

1 parameter1 parameter

Page 5: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

55

Function ExampleFunction Example

function printPhrase($phrase) function printPhrase($phrase)

{{

echo “$phrase</ br>”;echo “$phrase</ br>”;

}}

printPhrase(“Silly goose!”);printPhrase(“Silly goose!”);

Page 6: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

66

Returning ValuesReturning Values

A A return statementreturn statement returns a value to returns a value to the statement that called the functionthe statement that called the function

A function does not have to return a A function does not have to return a valuevalue

function averageNumbers($a, $b, $c) function averageNumbers($a, $b, $c) {{

$sumOfNumbers = $a + $b + $c;$sumOfNumbers = $a + $b + $c;$average = $sumOfNumbers / 3;$average = $sumOfNumbers / 3;return $average;return $average;

}}

Page 7: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

77

Function PracticeFunction Practice

1.1. Write a function that takes a name and Write a function that takes a name and prints “Hello, prints “Hello, namename!” !”

2.2. Write a function that returns the Write a function that returns the maximum of two values.maximum of two values.

3.3. Write a function that converts celsius to Write a function that converts celsius to fahrenheit (F=C*1.8+32).fahrenheit (F=C*1.8+32).

4.4. Write a function that takes a radius and Write a function that takes a radius and returns the circumference of a circle returns the circumference of a circle (C=PI*Diameter).(C=PI*Diameter).

Page 8: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

88

Understanding Variable ScopeUnderstanding Variable Scope

Variable scopeVariable scope • Where in your program a declared variable can Where in your program a declared variable can

be usedbe used• Can be either global or localCan be either global or local

Global variableGlobal variable • Declared outside a function and available to all Declared outside a function and available to all

parts of your programparts of your program Local variableLocal variable

• Declared inside a function and only available Declared inside a function and only available within that functionwithin that function

Page 9: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

99

Variable ScopeVariable Scope<?php<?php

$globalVar = "Global";$globalVar = "Global";function scopeExample()function scopeExample(){{

echo "<b>Inside function:echo "<b>Inside function:<br /></b>";<br /></b>";

$localVar = "Local";$localVar = "Local";echo "$localVar<br />";echo "$localVar<br />";global $globalVar;global $globalVar;echo "$globalVar<br /><br />";echo "$globalVar<br /><br />";

}}scopeExample();scopeExample();echo "<b>Outside function:echo "<b>Outside function:

<br /></b>"; <br /></b>";echo "$localVar<br />"; echo "$localVar<br />"; echo "$globalVar<br />";echo "$globalVar<br />";

?>?>

global keywordglobal keywordused insideused insidefunction to function to referencereferenceglobal variableglobal variable

Page 10: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1010

AutoglobalsAutoglobals

PHP includes predefined global arrays, PHP includes predefined global arrays, called called autoglobalsautoglobals or or superglobalssuperglobals

Autoglobals contain Autoglobals contain clientclient, , serverserver, and , and environmentenvironment information information

Autoglobals are Autoglobals are associative arraysassociative arrays • Elements are referred to with an alphanumeric Elements are referred to with an alphanumeric

key instead of an index numberkey instead of an index number• Example: Example: $_SERVER[“PHP_SELF”]$_SERVER[“PHP_SELF”]

Page 11: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1111

PHP AutoglobalsPHP Autoglobals

See http://us.php.net/reserved.variables for more information.

Page 12: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1212

Using $GLOBALSUsing $GLOBALS

<?php$globalVar = "Global";function scopeExample(){

echo "<b>Inside function:<br /></b>";$localVar = "Local";echo "$localVar<br />";echo $GLOBALS["globalVar"] , "<br /><br />";

}scopeExample();echo "<b>Outside function:<br /></b>";echo "$localVar<br />"; echo "$globalVar<br />";

?>

Page 13: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1313

Using $_SERVERUsing $_SERVER<?php<?php

echo "The name of the current script is ", echo "The name of the current script is ", $_SERVER["PHP_SELF"], "<br />";$_SERVER["PHP_SELF"], "<br />";

echo "The absolute path of the current script is: ", echo "The absolute path of the current script is: ", $_SERVER["SCRIPT_FILENAME"], "<br />";$_SERVER["SCRIPT_FILENAME"], "<br />";

echo "The name of the server on which this script is echo "The name of the server on which this script is executing is: ", $_SERVER["SERVER_NAME"], "<br />";executing is: ", $_SERVER["SERVER_NAME"], "<br />";

echo "This script was executed with the following server echo "This script was executed with the following server software: ", $_SERVER["SERVER_SOFTWARE"], "<br />";software: ", $_SERVER["SERVER_SOFTWARE"], "<br />";

echo "This script was executed with the following server echo "This script was executed with the following server protocol: ", $_SERVER["SERVER_PROTOCOL"];protocol: ", $_SERVER["SERVER_PROTOCOL"];

?>?>

Page 14: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1414

Using $_GET and $_POSTUsing $_GET and $_POST

$_GET$_GET and and $_POST$_POST allow you to allow you to access the values of forms that are access the values of forms that are submitted to a PHP scriptsubmitted to a PHP script

$_GET$_GET appends form data as one long appends form data as one long string to the URLstring to the URL

$_POST$_POST sends form data as a sends form data as a transmission separate from the URLtransmission separate from the URL

Page 15: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1515

$_GET Example$_GET Example

Note the values in the URL

<form method="get" action="processForm.php">Name:&nbsp<input type="text" name="name" size="20" /><br />Hometown:&nbsp<input type="text" name="town" size="20" /><br /><input type="submit" value="Submit">

</form><?php

echo "Hello, ", $_GET["name"], " from ", $_GET["town"], "!";?>

Page 16: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1616

$_POST Example$_POST Example

No values in the URL

<form method=“post" action="processForm.php">Name:&nbsp<input type="text" name="name" size="20" /><br />Hometown:&nbsp<input type="text" name="town" size="20" /><br /><input type="submit" value="Submit">

</form><?php

echo "Hello, ", $_POST["name"], " from ", $_POST["town"], "!";?>

Page 17: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1717

ifif Statements Statements

Used to execute specific programming code Used to execute specific programming code ifif a condition returns a condition returns truetrue

Syntax:Syntax: if (if (conditional expressionconditional expression))

statementstatement;; Example:Example:

$num = 5;$num = 5;if ($num == 5) // CONDITION IS TRUEif ($num == 5) // CONDITION IS TRUE{ { echo “The condition evaluates to true.</ br>”;echo “The condition evaluates to true.</ br>”;echo '$num is equal to ', “$num.</ br>”echo '$num is equal to ', “$num.</ br>”

}}echo “This statement always executes.</ br>”;echo “This statement always executes.</ br>”;

Page 18: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1818

if...elseif...else Statements Statements

An An elseelse clause executes when the condition clause executes when the condition in an in an if...elseif...else statement evaluates to statement evaluates to falsefalse

Syntax:Syntax:if (if (conditional expressionconditional expression) )

statementstatement;;elseelse

statementstatement;;

Example:Example:$Today = “Tuesday”;$Today = “Tuesday”;if ($Today == “Monday”)if ($Today == “Monday”)

echo “Today is Monday</ br>”;echo “Today is Monday</ br>”;elseelse

echo “Today is not Monday</ echo “Today is not Monday</ br>”;br>”;

Curly braces are not required Curly braces are not required when there is only one when there is only one

statement after the if or else.statement after the if or else.

Page 19: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

1919

Nested Nested ifif Statements Statements

One decision-making statement One decision-making statement may be contained within anothermay be contained within another

if ($_GET[“SalesTotal”] > 50)if ($_GET[“SalesTotal”] > 50){{

if ($_GET[“SalesTotal”] < 100)if ($_GET[“SalesTotal”] < 100){{

echo “Sales total is between 50 and echo “Sales total is between 50 and 100.</ br>”;100.</ br>”;

}}}}

Page 20: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2020

switchswitch Statements Statements Controls program flow by executing a specific Controls program flow by executing a specific

set of statements depending on the value of set of statements depending on the value of an expressionan expression

Compares the value of an expression to a Compares the value of an expression to a value in a value in a case labelcase label• casecase label can be followed by one or more label can be followed by one or more

statementsstatements• Each set of statements is usually followed by the Each set of statements is usually followed by the

keyword keyword breakbreak• The The defaultdefault label contains statements that label contains statements that

execute when the value of the expression does not execute when the value of the expression does not match any other match any other casecase label label

Page 21: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2121

switchswitch Statements Statements SyntaxSyntax

Switch (Switch (expressionexpression) ) {{case case label: label: statement(s)statement(s);;

break;break;case case labellabel::

statement(s)statement(s);;break;break;

......default:default:

statement(s)statement(s);;}}

ExampleExampleSwitch ($day) Switch ($day) {{

case 1case 1: : print “partridge”;print “partridge”; break;break;case 2:case 2: print “turtle print “turtle

doves”;doves”; break;break;......default:default: print “Invalid”;print “Invalid”;

}}

Page 22: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2222

Decision PracticeDecision Practice

Write a statement that prints “even” if a Write a statement that prints “even” if a variable num is even.variable num is even.

Write a statement that prints “even” if a Write a statement that prints “even” if a variable num is even, and “odd” variable num is even, and “odd” otherwise.otherwise.

Write a statement that prints “A” for a Write a statement that prints “A” for a grade of 90-100, “B” for 80-89, “C” for 70-grade of 90-100, “B” for 80-89, “C” for 70-79, “D” for 60-69 and “F” otherwise.79, “D” for 60-69 and “F” otherwise.

Write a switch statement that takes a Write a switch statement that takes a number and prints the corresponding number and prints the corresponding month, e.g. “January” for 1.month, e.g. “January” for 1.

Page 23: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2323

Repeating CodeRepeating Code

A A loop statementloop statement is a control structure that is a control structure that repeatedly executes a statement or a series of repeatedly executes a statement or a series of statements statements

Each repetition of a loop is called an Each repetition of a loop is called an iterationiteration Loop may execute Loop may execute whilewhile a condition is true or a condition is true or untiluntil a condition becomes true a condition becomes true

Four types of loops:Four types of loops:• while statements• do...while statements• for statements• foreach statements

Page 24: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2424

whilewhile Statements Statements

Repeats one or more statements Repeats one or more statements whilewhile a conditional expression evaluates to a conditional expression evaluates to truetrue

Syntax:Syntax: while (while (conditional expressionconditional expression) )

{{

statement(s);statement(s);

}}

Page 25: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2525

whilewhile Statement Example Statement Example

$Count = 1;$Count = 1;while ($Count <= 5) while ($Count <= 5) {{

echo “$Count<br />”;echo “$Count<br />”;++$Count;++$Count;

}}echo “You have printed 5 numbers.</ br>”;echo “You have printed 5 numbers.</ br>”;

Page 26: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2626

whilewhile Statement Example Statement Example

$Count = 10;$Count = 10;while ($Count > 0) while ($Count > 0) {{

echo “$Count<br />”;echo “$Count<br />”;--$Count;--$Count;

}}echo “We have liftoff.</ br>”;echo “We have liftoff.</ br>”;

Page 27: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2727

whilewhile Statements Example Statements Example

$Count = 1;$Count = 1;while ($Count <= 100) while ($Count <= 100) {{

echo “$Count<br />”;echo “$Count<br />”;$Count *= 2;$Count *= 2;

}}

Page 28: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2828

Infinite LoopsInfinite Loops

In an In an infinite loopinfinite loop, a loop statement , a loop statement never ends because its conditional never ends because its conditional expression is never falseexpression is never false

$Count = 1;$Count = 1;

while ($Count <= 10) while ($Count <= 10)

{{

echo “The number is $Count”;echo “The number is $Count”;

}}

Page 29: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

2929

do...whiledo...while Statements Statements

Executes a statement or statements Executes a statement or statements at least onceat least once

Repeats execution as long as Repeats execution as long as conditional expression is trueconditional expression is true

Syntax:Syntax:do do

{{

statementstatement(s);(s);

} while (} while (conditional expressionconditional expression););

Page 30: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3030

do...whiledo...while Example Example

$Count = 2;$Count = 2;

do do

{{

echo “The count is equal echo “The count is equal

to $Count</ br>”;to $Count</ br>”;

++$Count;++$Count;

} while ($Count < 2);} while ($Count < 2);

Page 31: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3131

do...whiledo...while Example Example

$DaysOfWeek = array(“Monday”, “Tuesday”, $DaysOfWeek = array(“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”);“Saturday”, “Sunday”);

$Count = 0;$Count = 0;do do {{

echo $DaysOfWeek[$Count], “<br />”;echo $DaysOfWeek[$Count], “<br />”;++$Count;++$Count;

} while ($Count < 7);} while ($Count < 7);

Page 32: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3232

forfor Statements Statements

Used to repeat one or more statements as Used to repeat one or more statements as long as a given condition is truelong as a given condition is true

Includes code that initializes a counter and Includes code that initializes a counter and changes its value with each iterationchanges its value with each iteration

Syntax:Syntax:

for (for (counter declaration and initializationcounter declaration and initialization; ; conditioncondition; ; update statement) update statement) {{

statement(s)statement(s);;} }

Page 33: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3333

forfor Statements Example Statements Example

$FastFoods$FastFoods == array(“pizza”,array(“pizza”, “burgers”,“burgers”, “french“french fries”, “tacos”, “fried chicken”);fries”, “tacos”, “fried chicken”);

for ($Count = 0; $Count < 5; ++$Count) for ($Count = 0; $Count < 5; ++$Count)

{{

echo $FastFoods[$Count], “<br />”;echo $FastFoods[$Count], “<br />”;

}}

Page 34: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3434

foreachforeach Statements Statements

Used to iterate or loop through the Used to iterate or loop through the elements in an arrayelements in an array

Does not require a counterDoes not require a counter Specify an array expression within a set Specify an array expression within a set

of parentheses following of parentheses following foreachforeach Syntax:Syntax:

foreach ($foreach ($array_namearray_name as $ as $variable_namevariable_name) )

{{

statements;statements;

}}

Page 35: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3535

foreachforeach Example Example

$animals = array(“lion”, “tiger”, $animals = array(“lion”, “tiger”, “monkey”);“monkey”);

foreach ($animals as $animal)foreach ($animals as $animal)

{{

echo “$animal<br />”;echo “$animal<br />”;

}}

Page 36: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3636

Loop PracticeLoop Practice

Using a do loop, do…while loop, and for Using a do loop, do…while loop, and for loop, perform each of the following tasks:loop, perform each of the following tasks:

• Print the numbers from 10 to 1 and then Print the numbers from 10 to 1 and then “Blastoff!” “Blastoff!”

• Add up the numbers from 1 to 10 and then Add up the numbers from 1 to 10 and then display the result.display the result.

Page 37: CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals

3737

SummarySummary

Functions are groups of statements that Functions are groups of statements that you can execute as a single unityou can execute as a single unit

Autoglobals contain client, server, and Autoglobals contain client, server, and environment informationenvironment information

Flow control determines the order in which Flow control determines the order in which program statements executeprogram statements execute

Decision logic includes if, if…else, and Decision logic includes if, if…else, and switchswitch

Loops include while, do…while, for, and Loops include while, do…while, for, and foreachforeach