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

Slides:



Advertisements
Similar presentations
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Creating PHP Pages Chapter 7 PHP Decisions Making.
Objectives Using functions to organize PHP code
PHP Conditions MIS 3501, Fall 2014 Jeremy Shafer Department of MIS Fox School of Business Temple University September 11, 2014.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
ITC 240: Web Application Programming
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
CSCI 116 Decisions & Validation. Overview Constants Boolean conditions Decision logic Form validation 2.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Control Structures II (Repetition)
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
CSCI 116 Functions.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Objectives You should be able to describe:
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
TODAY’S LECTURE Review Chapter 2 Go over exercises.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Arrays and Control Structures CST 200 – JavaScript 2 –
Decisions, Loops, and Arrays Achmad Arwan, S.Kom.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Jaeki Song ISQS6337 JAVA Lecture 04 Control Structure - Selection, and Repetition -
4 1 Array and Hash Variables CGI/Perl Programming By Diane Zak.
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.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
ㅎㅎ logical operator if if else switch while do while for Third step for Learning C++ Programming Repetition Control Structures.
PHP Constructs Advance Database Management Systems Lab no.3.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Introduction to PHP.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
STRUCTURED PROGRAMMING Selection Statements. Content 2  Control structures  Types of selection statements  if single-selection statement  if..else.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
JavaScript, Sixth Edition
LOOPS CHAPTER Topics  Four Types of Loops –while –do…while –for –foreach  Jump Statements in Loops –break –continue 2.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
 Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
Chapter 3: Decisions and Loops
CHAPTER 5 SERVER SIDE SCRIPTING
Expressions and Control Flow in JavaScript
JavaScript: Control Statements.
ITM 352 Flow-Control: Loops
Objectives In this chapter, you will:
Lesson 3. Controlling program flow. Loops. Methods. Arrays.
Presentation transcript:

CSCI 116 Week 3 Functions & Control Structures

2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals Decision logic Decision logic if statementsif statements if...else statementsif...else statements switch statementsswitch statements Loops Loops while statementswhile statements do...while statementsdo...while statements for and foreach statementsfor and foreach statements

3 Defining Functions Functions Functions Groups of statements that you can execute as a single unitGroups of statements that you can execute as a single unit Defining a function : Defining a function :<?php function name_of_function(parameters) { statements; statements;}?>

4 Function Parameters A parameter is an input to the function A parameter is an input to the function Parameters are placed within the parentheses that follow the function name Parameters are placed within the parentheses that follow the function name Not all functions accept parameters Not all functions accept parameters function average($num1, $num2) function printHello() function calcTax($price) 2 parameters 0 parameters 1 parameter

5 Function Example function printPhrase($phrase) { echo “$phrase ”; } printPhrase(“Silly goose!”);

6 Returning Values A return statement returns a value to the statement that called the function A return statement returns a value to the statement that called the function A function does not have to return a value A function does not have to return a value function averageNumbers($a, $b, $c) { $sumOfNumbers = $a + $b + $c; $average = $sumOfNumbers / 3; return $average; }

7 Function Practice 1. Write a function that takes a name and prints “Hello, name!” 2. Write a function that returns the maximum of two values. 3. Write a function that converts celsius to fahrenheit (F=C*1.8+32). 4. Write a function that takes a radius and returns the circumference of a circle (C=PI*Diameter).

8 Understanding Variable Scope Variable scope Variable scope Where in your program a declared variable can be usedWhere in your program a declared variable can be used Can be either global or localCan be either global or local Global variable Global variable Declared outside a function and available to all parts of your programDeclared outside a function and available to all parts of your program Local variable Local variable Declared inside a function and only available within that functionDeclared inside a function and only available within that function

9 Variable Scope <?php $globalVar = "Global"; function scopeExample() { echo " Inside function: "; $localVar = "Local"; echo "$localVar "; global $globalVar; echo "$globalVar "; }scopeExample(); echo " Outside function: "; echo "$localVar "; echo "$globalVar "; ?> global keyword used inside function to reference global variable

10 Autoglobals PHP includes predefined global arrays, called autoglobals or superglobals PHP includes predefined global arrays, called autoglobals or superglobals Autoglobals contain client, server, and environment information Autoglobals contain client, server, and environment information Autoglobals are associative arrays Autoglobals are associative arrays Elements are referred to with an alphanumeric key instead of an index numberElements are referred to with an alphanumeric key instead of an index number Example: $_SERVER[“PHP_SELF”]Example: $_SERVER[“PHP_SELF”]

11 PHP Autoglobals See for more information.

12 Using $GLOBALS <?php $globalVar = "Global"; function scopeExample() { echo " Inside function: "; $localVar = "Local"; echo "$localVar "; echo $GLOBALS["globalVar"], " "; } scopeExample(); echo " Outside function: "; echo "$localVar "; echo "$globalVar "; ?>

13 Using $_SERVER <?php echo "The name of the current script is ", $_SERVER["PHP_SELF"], " "; echo "The absolute path of the current script is: ", $_SERVER["SCRIPT_FILENAME"], " "; echo "The name of the server on which this script is executing is: ", $_SERVER["SERVER_NAME"], " "; echo "This script was executed with the following server software: ", $_SERVER["SERVER_SOFTWARE"], " "; echo "This script was executed with the following server protocol: ", $_SERVER["SERVER_PROTOCOL"]; ?>

14 Using $_GET and $_POST $_GET and $_POST allow you to access the values of forms that are submitted to a PHP script $_GET and $_POST allow you to access the values of forms that are submitted to a PHP script $_GET appends form data as one long string to the URL $_GET appends form data as one long string to the URL $_POST sends form data as a transmission separate from the URL $_POST sends form data as a transmission separate from the URL

15 $_GET Example Note the values in the URL Name:&nbsp Hometown:&nbsp <?php echo "Hello, ", $_GET["name"], " from ", $_GET["town"], "!"; ?>

16 $_POST Example No values in the URL Name:&nbsp Hometown:&nbsp <?php echo "Hello, ", $_POST["name"], " from ", $_POST["town"], "!"; ?>

17 if Statements Used to execute specific programming code if a condition returns true Used to execute specific programming code if a condition returns true Syntax: Syntax: if (conditional expression) if (conditional expression) statement ; Example: Example: $num = 5; if ($num == 5) // CONDITION IS TRUE { echo “The condition evaluates to true. ”; echo '$num is equal to ', “$num. ” } echo “This statement always executes. ”;

18 if...else Statements An else clause executes when the condition in an if...else statement evaluates to false An else clause executes when the condition in an if...else statement evaluates to false Syntax: Syntax: if (conditional expression) statement; else Example: Example: $Today = “Tuesday”; if ($Today == “Monday”) echo “Today is Monday ”; else echo “Today is not Monday ”; Curly braces are not required when there is only one statement after the if or else.

19 Nested if Statements One decision-making statement may be contained within another One decision-making statement may be contained within another if ($_GET[“SalesTotal”] > 50) { if ($_GET[“SalesTotal”] < 100) { echo “Sales total is between 50 and 100. ”; }}

20 switch Statements Controls program flow by executing a specific set of statements depending on the value of an expression Controls program flow by executing a specific set of statements depending on the value of an expression Compares the value of an expression to a value in a case label Compares the value of an expression to a value in a case label case label can be followed by one or more statementscase label can be followed by one or more statements Each set of statements is usually followed by the keyword breakEach set of statements is usually followed by the keyword break The default label contains statements that execute when the value of the expression does not match any other case labelThe default label contains statements that execute when the value of the expression does not match any other case label

21 switch Statements Syntax Syntax Switch (expression) { case label: statement(s); break; case label: statement(s); break;...default: } Example Example Switch ($day) { case 1: print “partridge”; break; case 2: print “turtle doves”; break;... default: print “Invalid”; }

22 Decision Practice Write a statement that prints “even” if a variable num is even. Write a statement that prints “even” if a variable num is even. Write a statement that prints “even” if a variable num is even, and “odd” otherwise. Write a statement that prints “even” if a variable num is even, and “odd” otherwise. Write a statement that prints “A” for a grade of , “B” for 80-89, “C” for 70-79, “D” for and “F” otherwise. Write a statement that prints “A” for a grade of , “B” for 80-89, “C” for 70-79, “D” for and “F” otherwise. Write a switch statement that takes a number and prints the corresponding month, e.g. “January” for 1. Write a switch statement that takes a number and prints the corresponding month, e.g. “January” for 1.

23 Repeating Code A loop statement is a control structure that repeatedly executes a statement or a series of statements A loop statement is a control structure that repeatedly executes a statement or a series of statements Each repetition of a loop is called an iteration Each repetition of a loop is called an iteration Loop may execute while a condition is true or until a condition becomes true Loop may execute while a condition is true or until a condition becomes true Four types of loops: Four types of loops: while statements do...while statements for statements foreach statements

24 while Statements Repeats one or more statements while a conditional expression evaluates to true Repeats one or more statements while a conditional expression evaluates to true Syntax: Syntax: while (conditional expression) while (conditional expression){statement(s); }

25 while Statement Example $Count = 1; while ($Count <= 5) { echo “$Count ”; ++$Count;} echo “You have printed 5 numbers. ”;

26 while Statement Example $Count = 10; while ($Count > 0) { echo “$Count ”; --$Count;} echo “We have liftoff. ”;

27 while Statements Example $Count = 1; while ($Count <= 100) { echo “$Count ”; $Count *= 2; }

28 Infinite Loops In an infinite loop, a loop statement never ends because its conditional expression is never false In an infinite loop, a loop statement never ends because its conditional expression is never false $Count = 1; while ($Count <= 10) { echo “The number is $Count”; }

29 do...while Statements Executes a statement or statements at least once Executes a statement or statements at least once Repeats execution as long as conditional expression is true Repeats execution as long as conditional expression is true Syntax: Syntax:do{ statement(s); } while (conditional expression);

30 do...while Example $Count = 2; do{ echo “The count is equal to $Count ”; ++$Count; } while ($Count < 2);

31 do...while Example $DaysOfWeek = array(“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”); $Count = 0; do{ echo $DaysOfWeek[$Count], “ ”; ++$Count; } while ($Count < 7);

32 for Statements Used to repeat one or more statements as long as a given condition is true Used to repeat one or more statements as long as a given condition is true Includes code that initializes a counter and changes its value with each iteration Includes code that initializes a counter and changes its value with each iteration Syntax: Syntax: for (counter declaration and initialization; condition; update statement) { statement(s); }

33 for Statements Example $FastFoods = array(“pizza”, “burgers”, “french fries”, “tacos”, “fried chicken”); for ($Count = 0; $Count < 5; ++$Count) { echo $FastFoods[$Count], “ ”; }

34 foreach Statements Used to iterate or loop through the elements in an array Used to iterate or loop through the elements in an array Does not require a counter Does not require a counter Specify an array expression within a set of parentheses following foreach Specify an array expression within a set of parentheses following foreach Syntax: Syntax: foreach ($array_name as $variable_name) {statements;}

35 foreach Example $animals = array( “ lion ”, “ tiger ”, “ monkey ” ); foreach ($animals as $animal) { echo “ $animal ” ; }

36 Loop Practice Using a do loop, do…while loop, and for loop, perform each of the following tasks: Using a do loop, do…while loop, and for loop, perform each of the following tasks: Print the numbers from 10 to 1 and then “Blastoff!”Print the numbers from 10 to 1 and then “Blastoff!” Add up the numbers from 1 to 10 and then display the result.Add up the numbers from 1 to 10 and then display the result.

37 Summary Functions are groups of statements that you can execute as a single unit Functions are groups of statements that you can execute as a single unit Autoglobals contain client, server, and environment information Autoglobals contain client, server, and environment information Flow control determines the order in which program statements execute Flow control determines the order in which program statements execute Decision logic includes if, if…else, and switch Decision logic includes if, if…else, and switch Loops include while, do…while, for, and foreach Loops include while, do…while, for, and foreach