Flow Control 10. Flow Control. Content. if Statement. Conditional Statements. if Statement. Example. if, if/else, switch for, while, do/while

Similar documents
Flow Control. Copyleft 2005, Binnur Kurt

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

Programming in C++ PART 2

What is PHP? [1] Figure 1 [1]

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Chapter 2: Functions and Control Structures

PHP 5 if...else...elseif Statements

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

C++ Programming: From Problem Analysis to Program Design, Third Edition

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

1/22/2017. Chapter 2. Functions and Control Structures. Calling Functions. Objectives. Defining Functions (continued) Defining Functions

Lecture 12. PHP. cp476 PHP

V3 1/3/2015. Programming in C. Example 1. Example Ch 05 A 1. What if we want to process three different pairs of integers?

COMPUTER PROGRAMMING LOOPS

Why Is Repetition Needed?

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP. Interactive Web Systems

Python - Variable Types. John R. Woodward

REPETITION CONTROL STRUCTURE LOGO

Theory of control structures

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

PhpT Point, Simply Easy Learning

Introduction to Bioinformatics

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

B. V. Patel Institute of BMC & IT 2014

PHP Introduction. Some info on MySQL which we will cover in the next workshop...

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Dept. of CSE, IIT KGP

CS 106 Introduction to Computer Science I

PHP 101. Function Junction. Mike Pavlak Solutions Consultant (815) All rights reserved. Zend Technologies, Inc.

Important Points about PHP:

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

204111: Computer and Programming

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Key Differences Between Python and Java

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

8. Control statements

Chapter 8. Statement-Level Control Structures

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

PHP 1. Introduction Temasek Polytechnic

Introduction To C#.NET

CS50 Supersection (for those less comfortable)

switch-case Statements

n Group of statements that are executed repeatedly while some condition remains true

Chapter 8. Statement-Level Control Structures

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Unit 3 Decision making, Looping and Arrays

CS 112 Introduction to Programming

CSC Software I: Utilities and Internals. Programming in Python

Examples of Using the ARGV Array. Loop Control Operators. Next Operator. Last Operator. Perl has three loop control operators.

CGS 3066: Spring 2015 JavaScript Reference

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

- Origins - Rasmus Lerdorf Developed to allow him to track visitors to his Web site

Chapter 3. Iteration

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

More Perl. CS174 Chris Pollett Oct 25, 2006.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Basic PHP. Lecture 19. Robb T. Koether. Hampden-Sydney College. Mon, Feb 26, 2108

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

CSCD 326 Data Structures I Hashing

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lexical Considerations

Operators. Java operators are classified into three categories:

Chapter 8. Statement-Level Control Structures ISBN

10 Control and Iteration

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

FORM 2 (Please put your name and form # on the scantron!!!!)

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Princeton University COS 333: Advanced Programming Techniques A Subset of PHP

Lecture 7 PHP Basics. Web Engineering CC 552

COMS 469: Interactive Media II

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

Accelerating Information Technology Innovation

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

CS201- Introduction to Programming Current Quizzes

JME Language Reference Manual

Iterators and blocks. Using iterators and blocks Iterate with each or use a for loop? Creating iterators

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

CS 106 Introduction to Computer Science I

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

1 Lexical Considerations

Object Oriented Software Design

Transcription:

Content 10 Flow Control if, if/, switch for, while, do/while Copyleft 2005, Binnur Kurt 513 Conditional Statements if Statement 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. In PHP we have two conditional statements: 1. if (...) statement - use this statement if you want to execute a set of code when a condition is true (and another if the condition is not true) 2. switch statement - use this statement if you want to select one of many sets of lines to execute If you want to execute some code if a condition is true and another code if a condition is false, use the if... statement. if (condition) code to be executed if condition is true; code to be executed if condition is false; 514 515 The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": $d=date("d"); if ($d=="fri") echo "Have a nice weekend!"; echo "Have a nice day!"; 516 if Statement If more than one line should be executed when a condition is true, the lines should be enclosed within curly braces: $x=10; if ($x==10) echo "Hello<br />"; echo "Good morning<br />"; 517

if ($x==10) if ($x==11) if ($x==12) if switch Statement If you want to select one of many blocks of code to be executed, use the Switch statement. switch (expression) case label1: code to be executed if expression = label1; case label2: code to be executed if expression = label2; default: code to be executed if expression is different from both label1 and label2; 518 519 This is how it works: First we have a single switch ($x) expression (most often a variable), that is evaluated once. The value of the expression is then compared case 1: with the values for each case in the structure. echo "Number 1"; If there is a match, the block of code associated with that case is executed. case 2: Use break to prevent the code from running into echo "Number 2"; the next case automatically. case 3: The default statement is used if none of the cases echo "Number 3"; are true. default: echo "No number between 1 and 3"; Looping Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements: 1. while - loops through a block of code if and as long as a specified condition is true 2. do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true 3. for - loops through a block of code a specified number of times 4. foreach - loops through a block of code for each element in an array 520 521 while Statement The while statement will execute a block of code if and as long as a condition is true. while (condition) The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs: $i=1; while($i<=5) echo "The number is ". $i. "<br />"; $i++; 522 523

do...while Statement The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. do while (condition); The following example will increment the value of i at least once, and it will continue incrementing the variable i while it has a value of less than 5: $i=0; do $i++; echo "The number is ". $i. "<br />"; while ($i<5); 524 525 for Statement for Statement The for statement is used when you know how many times you want to execute a statement or a list of statements. for (initialization; condition; increment) The for statement has three parameters. The first parameter is for initializing variables, The second parameter holds the condition, The third parameter contains any increments required to implement the loop. If more than one variable is included in either the initialization or the increment section, then they should be separated by commas. The condition must evaluate to true or false. 526 527 The following example prints the text "Hello World!" five times: for ($i=1; $i<=5; $i++) echo "Hello World!<br />"; <head><title>loop # 1</title></head> $i=2; while ($i<=10) echo $i<br> ; $i=$i+2 ; 528 529

<head><title> Loop # 2</title></head> for ($i=2; $i<=10 ; $i=$i+2) echo $i<br> ; <head><title>loop # 3</title></head> $i=1; while ($i<=10) if (($i%2)==0) echo "$i<br>" ; $i=$i+1 ; 530 531 <head><title> Loop # 4</title></head> $i=3; while ($i<=100) if ((($i%3)==0) (($i%7)==0)) echo "$i<br>" ; $i=$i+1 ; <head><title>prime Test</title></head> $number=3457; $isprime=true; for ($i=2; $i*$i<=$number ; $i=$i+1) if ($number%$i==0) echo "$number is not prime."; $isprime=false; if ($isprime) echo "$number is prime"; BIL101E Introduction to Computer & Information Systems 532 533 <head><title>prime Factorization</title></head> $number=3615; $first=true; echo "$number="; for ($i=2; $number>1 ;$i++) while ($number%$i==0) $number /= $i; if ($first) echo "$i"; $first=false; echo "*$i" ; foreach Statement Loops over the array given by the parameter. On each loop, the value of the current element is assigned to $value and the array pointer is advanced by one - so on the next loop, you'll be looking at the next element. foreach (array as value) 534 535

<? $array[0] = 1; $array[5] = "This is element 5"; $array[200] = 300; $array['one'] = "One"; $b = $array; $b[5] = 'Only in b'; $b does not overwrite $array foreach ($array as $elem) echo "Element is $elem<br>"; No numerical index Arrays in PHP are quite versatile We can use them as we use traditional arrays, indexing on integer values We can use them as hashes, associating a key with a value in an arbitrary index of the array In either case we access the data via subscripts In the first case the subscript is the integer index In the second case the subscript is the key value We can even mix the two if we'd like 536 537 can be created in a number of ways Explicitly using the array() construct Implicitly by indexing a variable Since PHP has dynamic typing, you cannot identify a variable as an array except by assigning an actual array to it If the variable is already set to a scalar, indexing will have undesirable results indexes the string! However, we can unset() it and then index it We can test a variable to see if it is set (isset() and if it is an array (is_array()) among other things Size will increase dynamically as needed Accessing Arrays can be done in many ways We can use direct access to obtain a desired item Good if we are using the array as a hash table or if we need direct access for some other reason For sequential access, the foreach loop was designed to work with arrays Iterates through the items in two different ways foreach ($arrayvar as $key => $value)» Gives both the key and value at each iteration foreach ($arrayvar as $value)» Gives just the next value at each iteration 538 539 Be careful in both cases data is iterated by the order it has been generated, not by index order Items accessed in the arrays using foreach are copies of the data, not references to the data So changing the loop control variable in the foreach loop in PHP does NOT change the data in the original array To do this we must change the value using indexing A regular for loop can also be used, but due to the non-sequential requirement for keys, this does not often give the best results The data in the array is not contiguous, so incrementing a counter for the next access will not work correctly unless the array index values are used in the "traditional" way We can also use other iterators such as next and each to access the array elements next gives us the next value with each call It moves to the next item, then returns it, so we must get the first item with a separate call (ex: use current()) $curr = current($a1); while ($curr): echo "\$curr is $curr <BR />\n"; $curr = next($a1); endwhile; 540 541

each returns an array of two items: A key field for the current key A value field for the current value It returns the next (key,value) pair, then moves, so the first item is no longer a special case while ($curr = each($a1)): $k = $curr["key"]; $v = $curr["value"]; echo "key is $k and value is $v <BR />\n"; endwhile; This function is preferable to next() if it is possible that FALSE or an empty string or 0 could be in the array The loop on the previous slide will stop for any of those values 542 Both of these iteration functions operate similar to the Iterator interface in Java Iterate through the data in the collection without requiring us to know how that data is actually organized Allow multiple iterations to proceed concurrently on the same underlying collection However, unlike in Java, if the array is changed during the iteration process, the current iteration continues Since new items are always added at the "end" of the array adding a new item during an iteration does not cause any data validity problems 543 The following example demonstrates a loop that will print the values of the given array: $arr=array("one", "two", "three"); foreach ($arr as $value) echo "Value: ". $value. "<br />"; 544