1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops.

Slides:



Advertisements
Similar presentations
You have been given a mission and a code. Use the code to complete the mission and you will save the world from obliteration…
Advertisements

Chapter 5: Control Structures II (Repetition)
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizards Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Lists, Loops, Validation, and More
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 4 Working with the Web.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizards Guide to PHP by David Lash.
1 Copyright © 2002 Pearson Education, Inc.. 2 Web Wizards Guide to CGI/Perl David Lash Chapter 3 Perl Basics.
Chapter 1 The Study of Body Function Image PowerPoint
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 5 Author: Julia Richards and R. Scott Hawley.
1 Copyright © 2010, Elsevier Inc. All rights Reserved Fig 2.1 Chapter 2.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Title Subtitle.
Local Customization Chapter 2. Local Customization 2-2 Objectives Customization Considerations Types of Data Elements Location for Locally Defined Data.
Determine Eligibility Chapter 4. Determine Eligibility 4-2 Objectives Search for Customer on database Enter application signed date and eligibility determination.
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
Addition Facts
Year 6 mental test 5 second questions
Year 6 mental test 10 second questions
The 5S numbers game..
Wednesday: 1/9 Finish Pendulum Lab (Tom). Thursday: 1/10 Finish 1.54 Pendulum Lab (Today) Lab: 1.55 Make a 1 Minute Clock (Today) HW: 1.2 worksheet (Tom)
1.
Order of Operations Lesson
Chapter 7: Arrays In this chapter, you will learn about
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 10 Arrays and Tile Mapping Starting Out with Games & Graphics.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Data Structures: A Pseudocode Approach with C
Chapter 24 Lists, Stacks, and Queues
ABC Technology Project
Day of the week 9:00 – 10:00 10: :00 12: :00 13: :00 14: :00 15: :00 16:00 – 17:00 17: :00 18:00 – 19:00 19:00 – 20:00.
3 Logic The Study of What’s True or False or Somewhere in Between.
Chapter 4 Systems of Linear Equations; Matrices
15-1 Copyright © 2013 Pearson Education, Inc. publishing as Prentice Hall Chapter 15 Money and Banking.
Review Pseudo Code Basic elements of Pseudo code
Copyright © 2013, 2009, 2006 Pearson Education, Inc.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Squares and Square Root WALK. Solve each problem REVIEW:
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
Lets play bingo!!. Calculate: MEAN Calculate: MEDIAN
1 Chapter 4 The while loop and boolean operators Samuel Marateck ©2010.
Chapter 5 Test Review Sections 5-1 through 5-4.
Project 6: Working with If Statements Essentials for Design JavaScript Level One Michael Brooks.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Slide R - 1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Prentice Hall Active Learning Lecture Slides For use with Classroom Response.
Addition 1’s to 20.
25 seconds left…...
Week 1.
Types of selection structures
We will resume in: 25 Minutes.
Pointers and Arrays Chapter 12
How Cells Obtain Energy from Food
FINAL EXAMINATION SCHEDULE SPRING 2009 MAY 15 – MAY 22 NOTE: A class that meets at more than one of the times on this final examination schedule will take.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 13 – Salary Survey Application: Introducing.
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 10.
Slide 3-1 CHAPTER 3 Conditional Statements Objectives To learn to use conditional test statements to compare numerical and string data values To learn.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
Slide 5-1 CHAPTER 5 Using Arrays for List Data Objectives To understand the benefits of using arrays in PHP To learn how to create and use sequential.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8.
Chapter 17 Arrays Perl to denote an array, for = (10, 20, 30, 50); Array subscripts are number from 0. Array elements require scalar.
The Web Wizard’s Guide to PHP
Presentation transcript:

1 Copyright © 2002 Pearson Education, Inc.

2 Chapter 5 List Variables and Loops

3 Copyright © 2002 Pearson Education, Inc. Objectives l Describe how list variables work l Describe four types of Perl looping statements l Explain how logical conditional operators are used

4 Copyright © 2002 Pearson Education, Inc. Lists Advantages l Using list variables enable programs to: »Include a flexible number of list elements. You can add items to and delete items from lists on the fly in your program. »Examine each element more concisely. Can use looping constructs (described later) with list variables to work with list items in a very concise manner. »Use special list operators and functions. Can use to determine list length, output your entire list, and sort your list, & other things.

5 Copyright © 2002 Pearson Education, Inc. Creating List Variables l Suppose wanted to create a list variable to hold 4 student names: Creates list with values Johnson, Jones, Jackson, and Jefferson

6 Copyright © 2002 Pearson Education, Inc. Creating List Variables Of Scalars l Suppose wanted to create a list variable to hold 4 student grades (numerical = ( 66, 75, 85, 80 ); Creates list with values 66, 75, 85, 80.

7 Copyright © 2002 Pearson Education, Inc. Referencing List Items l Items within a list variable are referenced by a set of related scalar variables For example, $students[0], $students[1], $students[2], and $students[3] l Reference in a variable name/subscript pair:

8 Copyright © 2002 Pearson Education, Inc. Referencing List Items - II l Subscripts can be whole numbers, another variable, or even expressions enclosed within the square brackets. l Consider the following example: = (ketchup, mustard, pickles, lettuce ); print $preferences[$i] $preferences[$i-1] $preferences[$i-2] $preferences[0]; l Outputs the list in reverse order: lettuce pickles mustard ketchup

9 Copyright © 2002 Pearson Education, Inc. Creating List Variables Of Scalars l Suppose wanted to create a list variable to hold 4 student grades (numerical = ( 66, 75, 85, 80 ); Creates list with values 66, 75, 85, 80.

10 Copyright © 2002 Pearson Education, Inc. Changing Items In A List Variable l Change values in a list variable and use them in expressions like other scalar variables. For example: = ( 75, 65, 85, 90); »$scores[3] = 95; »$average = ( $scores[0] + $scores[1] + » $scores[2] + $scores[3] ) / 4; The third line sets $average equal to ( ) / 4that is, to 80.

11 Copyright © 2002 Pearson Education, Inc. A Complete List Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Menu Choice'); = ('Meat Loaf', 'Meat Pie', 'Minced Meat', 'Meat Surprise' ); 5. $item = int(rand(4)); 6. print ' '; 7. print " What do you want to eat for dinner? "; 8. print br, "Our special is $menu[$item] "; 9. print br, ' ', "$menu[0]"; 10. print br, ' ', "$menu[1]"; 11. print br, ' ', "$menu[2]"; 12. print br, ' ', "$menu[3]"; 13. print br, ' '; 14.print ' ', end_html

12 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

13 Copyright © 2002 Pearson Education, Inc. Outputting the Entire List Variable Output all of the elements of a list variable by using the list variable with print l For = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ); print "My work week l Would output the following: »My work week is Monday Tuesday Wednesday Thursday Friday

14 Copyright © 2002 Pearson Education, Inc. Getting the Number in a List Variable l Use Range operator to find last element of list l For = ( 66, 75, 85, 80 ); $last_one = $grades[$#grades];

15 Copyright © 2002 Pearson Education, Inc. Using Range Operator for list length l Ranger operator is always 1 less than the total number in the list »(since list start counting at 0 rather than = (Monday, Tuesday, Wednesday, Thursday, Friday ); $daysLong = $#workWeek + 1; print My work week is $daysLong days long; l Would output the following message: My work week is 5 days long.

16 Copyright © 2002 Pearson Education, Inc. Using Range Operator for list length 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html("Got Your Preference"); = ("Meat Loaf", "Meat Pie", "Minced Meat", "Meat Surprise" ); 5. $response = param('eat'); 6. print " You 7. $menuLen = $#menu + 1; 8. print br, "We had $menuLen items available"; 9. print br, "These items end_html;

17 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

18 Copyright © 2002 Pearson Education, Inc. A Better Way to Get List Length l You can also find the length of a list variable by assigning the list variable name to a scalar variable. For example, the following code assigns to $size the number of elements in the list :

19 Copyright © 2002 Pearson Education, Inc. Adding and Removing List Items shift() and unshift() : add/remove elements from the beginning of a list. »shift() removes an item from the beginning of a list. For = (Monday, Tuesday, Wednesday,Thursday, Friday ); $dayOff = print "dayOff= $dayOff »Would output the following: dayOff= Monday workWeek=Tuesday Wednesday Thursday Friday

20 Copyright © 2002 Pearson Education, Inc. Adding and Removing List Items » unshift() adds an element to the beginning of the list For = (Monday, Tuesday, Wednesday, Thursday, Friday ); Sunday); print workWeek is now »would output the following: workWeek is now =Sunday Monday Tuesday Wednesday Thursday Friday

21 Copyright © 2002 Pearson Education, Inc. Adding and Removing List Items pop() and push( ) : add/remove elements from the end of a list. »shift() removes an item from the end of a list. For = (Monday, Tuesday, Wednesday, Thursday, Friday ); $dayOff = »Would output the following: dayOff= Friday workWeek=Monday Tuesday Wednesday Thursday

22 Copyright © 2002 Pearson Education, Inc. Adding and Removing List Items » push() adds an element to the end of the list For = (Monday, Tuesday, Wednesday, Thursday, Friday ); Saturday); print workWeek is now »would output the following: workWeek is now =Monday Tuesday Wednesday Thursday Friday Saturday

23 Copyright © 2002 Pearson Education, Inc. Extracting Multiple List Values l So for we have accessed one item at a time from a list variable. For = ( 'hot dogs, 'ketchup', 'lettuce', 'celery'); $essentials 2 ]; print "essentials=$essentials"; l would output: essentials=lettuce

24 Copyright © 2002 Pearson Education, Inc. Extracting Multiple List Values l If you use multiple subscripts for a list variable, you will extract a sub-list with the matching list items. l For = ( 'hot dogs, 'ketchup', 'lettuce', 2, 3 ]; print l The output of this code is essentials=lettuce celery

25 Copyright © 2002 Pearson Education, Inc. Extracting Multiple List Values l In a similar fashion, you can use a list variable as an index into another list variable. l Consider the following = ( 'hot dogs, 'ketchup', 'lettuce', = ( 0, 3 = ]; print l The output of this code is essentials=hot dogs celery »Useful with certain HTML form elements.

26 Copyright © 2002 Pearson Education, Inc. Example Multiple Arguments 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header; = ('USA', 'China', 'Canada', 'Mexico' ); 5. print '<FORM ACTION=" bin/C5/multichoice.cgi METHOD="POST">'; 6. print ' What countries have you visited?'; 7. print '<INPUT TYPE="checkbox" NAME="places" VALUE="0">', $menu[0]"; 8. print '<INPUT TYPE="checkbox" NAME="places" VALUE="1" checked>', "$menu[1]"; 9. print '<INPUT TYPE="checkbox" NAME="places" VALUE="2">', "$menu[2]"; 10. print '<INPUT TYPE="checkbox" NAME="places" VALUE="3">', "$menu[3]"; 11. print br, ' '; 12. print ' ', end_html;

27 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

28 Copyright © 2002 Pearson Education, Inc. Lists of Lists (or multidimensional lists) l Some data are best represented by a list of lists

29 Copyright © 2002 Pearson Education, Inc. Accessing Individual Items l Use multiple subsripts to access individual items »The first subscript indicates the row in which the item appears, and »the second subscript identifies the column where it is found. »In the preceding example, $Inventory[0][0] points to AC1000, $ Inventory[1][0] points to AC1001, and $Inventory[2][0] points to AC1002

30 Copyright © 2002 Pearson Education, Inc. A Partial = ( [ 'AC1000', 'Hammer', 122, ], [ 'AC1001', 'Wrench', 344, 5.50 ], [ 'AC1002', 'Hand Saw', 150, 10.00] ); $numHammers = $Inventory[0][2]; $firstPartNo = $Inventory[0][0]; $Inventory[0][3] = 15; print $numHammers, $firstPartNo, $Inventory[0][3]; l This would output 122, AC1000, 15

31 Copyright © 2002 Pearson Education, Inc. A Complete Example... Suppose the following HTML code creates radio buttons and sets CGI variable item (0-3) l The output is sent to bin/C5/GetInvent.cgi. Hammers Wrenches Hand Saws Screw Drivers

32 Copyright © 2002 Pearson Education, Inc. Receiving CGI/Perl Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Inventory Answer'); 4. # Inventory: PartNO, Item, Num In Stock, Price 5. $PRTNO=0; $ITEM=1; $NUM=2; $PRICE=3; = ( [ 'AC1000', 'Hammers', 122, 12 ], [ 'AC1001', 'Wrenches', 344, 5 ], [ 'AC1002', 'Hand Saws', 150, 10], [ 'AC1003', 'Screw Drivers', 250, 2] ); 7. $pick=param('item'); 8. if ( $pick >= 0 && $pick <= 3 ) { 9. print "Yes we have $Inventory[$pick][$ITEM]."; 10. print br, "In fact we have $Inventory[$pick][$NUM] of them."; 11. print br, "They are $Inventory[$pick][$PRICE] dollars."; 12. } else { "print sorry we do not have that item" } 13. print end_html;

33 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

34 Copyright © 2002 Pearson Education, Inc. Looping Statements l Advantages of using loops: »Your programs can be much more concise. When similar sections of statements need to be repeated in your program, you can often put them into a loop and reduce the total number of lines of code required. »You can write more flexible programs. Loops allow you to repeat sections of your program until you reach the end of a data structure such as a list or a file (covered later).

35 Copyright © 2002 Pearson Education, Inc. Advantages of Using Loops

36 Copyright © 2002 Pearson Education, Inc. The Perl Looping Constructs l Perl supports four types of looping constructs: »The for loop » The foreach loop »The while loop »The until loop l Each type of loop is described below.

37 Copyright © 2002 Pearson Education, Inc. The for loop You use the for loop to repeat a section of code a specified number of times. »(typically used when you know how many times to repeat)

38 Copyright © 2002 Pearson Education, Inc. 3 Parts to the for Loop The initialization expression defines the initial value of a variable used to control the loop. ( $i is used above with value of 0). The loop-ending condition defines the condition for termination of the loop. It is evaluated during each loop iteration. When false, the loop ends. (The loop above will repeat as long as $i is less than $max). The iteration expression is evaluated at end of each loop iteration. (In above loop the expression $i++ means to add 1 to the value of $i during each iteration of the loop. )

39 Copyright © 2002 Pearson Education, Inc. Consider the following program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(For Loop); 4. $start = param ('start'); 5. $end = param ( 'end'); 6. print '<TABLE BORDER=1> Numb Sqr Cubed '; 7. for ( $i = $start; $i < $end; $i++ ) { 8. $i_sq=$i**2; 9. $i_cubed=$i**3; 10. print " $i $i_sq $i_cubed "; 11. } 12. print " That is the end and i=$i"; 13. print end_html;

40 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

41 Copyright © 2002 Pearson Education, Inc. The foreach Loop The foreach loop is typically used to repeat a set of statements for every element in a list. = (A, B, C); »Then $item would A then B then C.

42 Copyright © 2002 Pearson Education, Inc. A For Each Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(' A foreach Example'); = ( 3, 6, 9 ); 5. $uinput = param( 'guess' ); 6. $ctr=0; $found=0; 7. foreach $item ) { 8. $ctr=$ctr+1; 9. if ( $item == $uinput ) { 10. print "Number $item. Item found was number $ctr "; 11. $found=1; 12. last; 13. } 14. } 15. if ( $found ) { 16. print " I checked $ctr item(s)."; 17. } else { 18. print " Your guess, $uinput was NOT FOUND! I checked $ctr item(s)."; 19. }

43 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

44 Copyright © 2002 Pearson Education, Inc. The while Loop You use a while loop to repeat a section of code as long as a test condition remains true.

45 Copyright © 2002 Pearson Education, Inc. Consider The Following #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(' A While Example'); 4. $upick=param('upick'); 5. $ctr = 1; 6. print ( " Numb of times to find $upick " ); 7. print ( ' Numb Rand ' ); 8. $rnum= int(rand(10)); 9. while ( $rnum != $upick ) { 10. print (" $ctr $rnum "); 11. $ctr = $ctr + 1; 12. $rnum= int(rand(10)); 13. } 14. print (" $ctr $rnum "); 15. print (' ', br, "FOUND in $ctr times random=$rnum" );

46 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

47 Copyright © 2002 Pearson Education, Inc. The until Loop Operates just like the while loop except that it loops as long as its test condition is false and continues until it is true

48 Copyright © 2002 Pearson Education, Inc. Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(' A While Example'); 4. $upick=param('upick'); 5. $ctr = 1; 6. print ( " Numb of times to find $upick " ); 7. print ( ' Numb Rand ' ); 8. do { 9. $rnum= int(rand(10)); 10. print (" $ctr $rnum "); 11. $ctr = $ctr + 1; 12. } until ( $rnum == $upick ); 13. print (' ', br, "FOUND in $ctr times random=$rnum" );

49 Copyright © 2002 Pearson Education, Inc. Creating Compound Conditionals logical conditional operators can test more than one test condition at once when used with if statements, while loops, and until loops l For example, while ( $x > $max && $found ne TRUE )

50 Copyright © 2002 Pearson Education, Inc. Some basic Conditional Operators && the AND operator - Both tests must be true: while ( $ctr < $max && $flag == 0 ) { || the OR operator. Either test is true. if ( $name eq SAM || $name eq MITCH ) { ! the NOT operator. Condition is false. if ( !$FLAG == 0 )

51 Copyright © 2002 Pearson Education, Inc. Consider the following #!/usr/bin/perl 2. use CGI ':standard'; = (1, 7); 4. print header, start_html('My Personal Safe'); 5. $in1 = param( 'pick1' ); 6. $in2 = param( 'pick2' ); 7. if (( $in1 == $safe[0] ) && ( $in2 == $safe[1])){ 8. print "Congrats you got the combo"; 9. } 10. else { 11. print "Sorry you are wrong! "; 12. print "You guessed $in1 and $in2 "; 13. } 14. print end_html;

52 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

53 Copyright © 2002 Pearson Education, Inc. Summary l List variables offer a way to organize data in your program into one list instead of using individual scalar variables. »Data elements within a list can be accessed by a common variable name, which is made up of two parts: a variable name and subscript values. l Using list variables enables you to add and delete list items on the fly in your programs, use loop constructs to examine and operate on each item in your list, and utilize special list operators and functions.

54 Copyright © 2002 Pearson Education, Inc. Summary Loops can be especially useful for examining and operating on data organized into lists. Loop statements include the for, foreach, while, and until loops. l The logical operators can be used to carry out compound tests within a conditional test statement. –The logical AND operator, &&, evaluates to true when both conditions are true. – The logical OR operator, ||, evaluates to true when either condition is true. –The logical NOT operator, !, evaluates to true when the test condition is false.

55 Copyright © 2002 Pearson Education, Inc. Summary l The logical operators can be used to carry out compound tests within a conditional test statement. –The logical AND operator, &&, evaluates to true when both conditions are true. – The logical OR operator, ||, evaluates to true when either condition is true. –The logical NOT operator, !, evaluates to true when the test condition is false.