Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13.

Slides:



Advertisements
Similar presentations
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.
Advertisements

CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
Tonight’s JavaScript Topics 1 Conditional Statements: if and switch The Array Object Looping Statements: for, while and do-while.
Creating PHP Pages Chapter 7 PHP Decisions Making.
Objectives Using functions to organize PHP code
1 CS101 Introduction to Computing Lecture 23 Flow Control & Loops (Web Development Lecture 8)
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Control Structures: continued.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 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.
CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Introduction to JavaScript for Python Programmers
JavaScript Switch Statement. Switch JavaScript Switch Statement If you have a lot of conditions, you can use a switch statement instead of an if…elseif…
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
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.
4 1 Array and Hash Variables CGI/Perl Programming By Diane Zak.
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.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Decision Making with Control Structures and Statements (non-audio version) © Dr. David.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
L OO P S While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript, Fourth Edition
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
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.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Control Structures, Blocks and Compound Statements A good programming language allows you to control the flow of your program in three ways: - execute.
Working with Loops, Conditional Statements, and Arrays.
IS2802 Introduction to Multimedia Applications for Business Lecture 4: JavaScript, Loops, and Conditional Statements Rob Gleasure
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and Conditional Statements Creating a Monthly Calendar.
JavaScript and Ajax (Control Structures) Week 4 Web site:
JavaScript, Sixth Edition
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
REPETITION CONTROL STRUCTURE
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
Chapter 5: Control Structures II
JavaScript: Control Statements I
Chapter 6: Conditional Statements and Loops
JavaScript: Control Statements.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
JavaScript: Control Statements I
ITM 352 Flow-Control: Loops
Arrays, For loop While loop Do while loop
Control Structures Functions Decision making Loops
T. Jumana Abu Shmais – AOU - Riyadh
Objectives In this chapter, you will:
M150: Data, Computing and Information
CIS 136 Building Mobile Apps
Presentation transcript:

Arrays and Control Structures CST 200 – JavaScript 2 –

Objectives Learn how to store data in arrays Use if statements, if...else statements, and switch statements to make decisions Nest one if statement in another Use while statements, do... while statements, and for statements to repeatedly execute code Use continue statements to restart a looping statement 2

Storing Data in Arrays So far, we have seen how to declare and use variables to store single pieces of information var cellPhone = "Samsung Epic"; There are times, however, when we want to store groups or lists of information in one place An array is used to represent a group, or list of information by a single variable name An array is like a collection of variables stored in one variable 3

Declaring and Initializing Arrays JavaScript represents arrays with the Array object The Array object contains a special constructor named Array() – A constructor is a special type of function used to create a new object Each item in stored in an array is called an element Syntax for creating an array var arrayName = new Array(number of elements); 4

Declaring and Initializing Arrays (cont) Examples: – Create an array named cellPhones var cellPhones = new Array(); – Create an array named cellPhones having 10 elements var cellPhones = new Array(10); Index – Element’s numeric position within the array – Array element numbering Starts with index number of zero (0) 5

Declaring and Initializing Arrays (cont) Example: Create an array named cellPhones having 10 elements var cellPhones = new Array(10); 6 keyword new Array( ) constructor Number of elements to be stored in array

Declaring and Initializing Arrays (cont) After declaring an array, we can then assign values to individual elements of the array – Include the array index for an individual element Example: – Assign values to first three elements of the cellPhones array 7 cellPhones[0] = "BlackBerry Storm 9530";// first element cellPhones[1] = "LG VX8360";// second element cellPhones[2] = "Motorola MOTO W755";// third element Notice: the first array element has the index 0

Declaring and Initializing Arrays (cont) When we first create an array, we don't have to specify the number of elements We can then add new elements to the array as necessary, and the array size will change dynamically var cellPhones = new Array(); cellPhones[0] = "BlackBerry Storm 9530"; cellPhones[1] = "LG VX8360"; 8

Declaring and Initializing Arrays (cont) We can also assign values to an array when the array is created var cellPhones = new Array( "BlackBerry Storm 9530", "LG VX8360", "Motorola MOTO W755"); 9

Declaring and Initializing Arrays (cont) Basic rule of thumb when creating arrays – Only declare number of array elements if exact number of elements the array will store is known In JavaScript each element on an array can contain a value with a different data type Example: var myData = new Array(); myData[0] = "Seth"; // string value myData[1] = 89;// numeric value myData[2] = true;// boolean value 10

Accessing Element Information To get or set the value of an array element, we use the array name followed by the element index in brackets To assign or modify array values: cellPhones[0] = "LG UX5500"; cellPhones[1] = "LG L55C"; To get array element values: document.write( cellPhones[0] ); document.write( cellPhones[1] ); 11 index

Determining the Number of Elements in an Array The Array class has a length property that stores the number of elements in an array Syntax array_name.length; Example: var shopList = new Array( ); shopList[0] = "eggs"; shopList[1] = "bread"; shopList[2] = "cheese"; shopList[3] = "apple juice"; document.write("shopList array size: " + shopList.length ); 12

Exercise – Web Console Use Web Console to type the following statements and expressions (one at a time, press Enter after each): var favCities = new Array(); favCities[0] = "Boston"; favCities[1] = "NYC"; favCities[2] = "Houston"; favCities[0]; "I love going to " + favCities[1] + " and " + favCities[2]; favCities[6] = "San Diego"; favCities; favCities[4] favCities.length; 13

Array Review #1 Practice creating and assigning values to an array: Write a separate statement to perform each action below: i.Declare an array named myFriends ii.Assign a string value of your friends name to the first array element (ex: "Jim Perkins" ) iii.Assign another friend to the second array element iv.Assign another friend to the third array element 14

Array Review #2 Practice creating and assigning values to an array, and printing the values of an array : Write a separate statement to perform each action below: i.Declare an array called questions ii.Assign a string value of a question into the first array element (ex: "What is your name?" ) iii.Assign another question to the second array element iv.Use the document.write( ) method to output the second array element value v.Use the window.alert( ) method to output the first array element value 15

Making Decisions All programming languages contain control structures to dictate the control flow of a program Decision-making control structures enable programs to make decisions, and perform different actions based on the decisions We will use the if, if-else, switch, while, do while and for statements to make decisions and modify control flow 16

if Statements Used to execute specific programming code if conditional expression evaluates to true Syntax if (conditional expression) statement; After the if statement executes: – Any subsequent code executes normally 17

18 var age = 25; if ( age == 25) window.alert("The var age is 25"); // do something else if Statements (cont) Note the special == equivalence operator

if...else Statements (cont) Can use command blocks to specify multiple statements should be executed within if...else statement Syntax 19 if (conditional expression) { statements; } else { statements; }

if Statements (cont) Use a command block to specify multiple statements should be executed if condition evaluates to true – Curly brackets { } identify start and end of command block 20 var age = 25; if ( age == 25) { window.alert("The var age is 25"); window.alert("25 is a good age"; window.alert("25 is the new 18"); } // do something else

If Review Practice writing an if statement: Assume the statement: var age = prompt("Enter age:"); Write an if – else statement to test whether age is >= 16 and output "you are driving age" or "you are NOT driving age" 21

if...else Statements Executes one action if the condition is true and a different action if the condition is false Syntax for an if... else statement if (conditional expression) statement; else statement; 22

if...else Statements (cont) Example: 23 var today = "Tuesday" if (today == "Monday") document.write("Today is Monday"); else document.write("Today is not Monday");

If – else Review Practice writing an if – else statement: Assume the statement: var rating = prompt("Enter rating:"); Write an if – else statement to test whether rating is <= 50 and output "not good", else if grade is <= 75 output "ok" else output "great job" 24

Nested if and if...else Statements We can nest decision-making structures, or place one decision-making statement inside another decision-making statement Nested if statement – An if statement contained within an if statement or within an if...else statement Nested if...else statement – An if...else statement contained within an if statement or within an if...else statement 25

Nested if and if...else Statements (cont) Example: 26 var salesTotal = prompt("What is the sales total?"); if (salesTotal > 50){ if (salesTotal < 100) { alert("The sales total is between 50 and 100."); }

switch Statements Controls program flow by executing a specific set of statements based on the value of an expression Compares expression value to one or more values contained within case labels 27

switch Statements (cont) Syntax 28 switch (expression) { case label: statement(s); case label: statement(s);... default: statement(s); }

switch Statements (cont) Example: 29 var age = prompt("Please enter age: "); switch ( age ) { case 25: alert("25 is a good age"); alert("lots of fun"); case "thirty": alert("Thirty is a good age"); case 40: alert("40 is a great age"); default: alert("that is a good age"); }

switch Statements (cont) When a switch statement executes: – Value returned by the expression is compared to each case label in the order in which it is encountered default label – Executes when the value returned by the switch statement expression does not match a case label break statement – Used to exit a control structure JavaScript, Fifth Edition30

31 function city_location(americanCity) { switch (americanCity) { case "Boston": return "Massachusetts"; break; case "Chicago": return "Illinois"; break; case "Los Angeles": return "California"; break; case "New York": return "New York"; break; default: return "United States"; } switch Statements (cont)

switch Review Practice writing a switch statement: Assume the statement: var cheese = prompt(“Enter fav cheese:”); Use the table below to write a switch statement that displays the message on the right, based on the input: 32 cheddar“cheddar is great for mac n cheese” provolone“provolone is great for sandwiches” swiss“swiss is not my favorite” default“I never heard of that cheese”

Repeating Code We use loop statement to repeatedly execute a statement or a series of statements While a specific condition is true or until a specific condition becomes true Three types of loop statements – while statements – do...while statements – for statements 33

while Statements while statement repeats a statement or series of statements as long as a given conditional expression evaluates to true Syntax while (conditional expression) { statement(s); } Each repetition of a looping statement is called an iteration 34

while Statements (cont’d.) When using a loop we need a special variable called a counter, to increment (increase) or decrement (decrease) within each loop iteration Examples: – while statement using an increment operator – while statement using a decrement operator – while statement using the *= assignment operator 35

36 var x = 1; while ( x <= 5) { document.write( x + " "); ++x; } document.write(" You have printed 5 numbers. "); while Statements (cont) Note the special ++ increment operator ++ increment operator adds 1 to the variable

37 var count = 10; while (count > 0) { document.write(count + " "); --count; } document.write(" We have liftoff. "); while Statements (cont) Note the special -- decrement operator -- decrement operator subtracts 1 from the variable

38 var count = 1; while (count <= 100) { document.write(count + " "); count *= 2; } while Statements (cont) Note the special *= multiplication assignment operator count *= 2 is the same as count = count * 2

while Statements (cont) If we are not careful, we can program in infinite loop, a loop statement that never ends – The loop will never end if the conditional expression never evaluates to false – Example (do NOT try): 39 var count = 1; while (count <= 10) { window.alert("The number is " + count + "."); } What is wrong with the loop?

while Review Practice writing a while statement: Write a while statement that displays the numbers 1 through 50 40

do...while Statements do...while statement – Executes a statement or statements once – Then repeats the execution as long as a given conditional expression evaluates to true Syntax 41 do { statement(s); } while (conditional expression);

do...while Statements (cont) Example: 42 var count = 0; do { document.write("The count is: " + count ); ++count; } while (count < 5);

for Statements for statement – Repeats a statement or series of statements as long as a given conditional expression evaluates to true – Can also include code that initializes a counter and changes its value with each iteration Syntax 43 for (counter declaration and initialization; condition; update statement) { statement(s); }

for Statements (cont) The steps the JavaScript interpreter performs when it encounters a for loop 1. Declare and initialize counter variable 2. Evaluate for loop condition 3. If condition evaluation in Step 2 returns true: for loop statements executes, Step 4 occurs, and the process starts over again with Step 2 If condition evaluation in Step 2 returns value of false: for statement ends Next statement following the for statement executes 4. Perform update statement in the for statement 44

for Statements (cont’d.) Example: 45 var daysOfWeek = new Array(); daysOfWeek[0] = "Monday"; daysOfWeek[1] = "Tuesday"; daysOfWeek[2] = "Wednesday"; daysOfWeek[3] = "Thursday"; daysOfWeek[4] = "Friday"; daysOfWeek[5] = "Saturday"; daysOfWeek[6] = "Sunday"; for (var count = 0; count < daysOfWeek.length; ++count) { document.write(daysOfWeek[count] + " "); }

for Review #1 Practice working with for statements: What is output by the following for statement? for (var x = 0; x < 5; ++x) { document.write( x * 5 ); } 46

for Review #2 Practice working with for statements: What is output by the following for statement? for (var y = 9; y > 4; --y) { document.write( y - 5 ); } 47

Using CONTINUE Statements to Restart Execution continue statement – Halts a looping statement, and restarts the loop with a new iteration – Used to stop a loop for the current iteration Examples: – for loop with a continue statement – for loop with a break statement 48

49 var brightStars = new Array(); brightStars[0] = "Sirius"; brightStars[1] = "Canopus"; brightStars[2] = "Arcturus"; brightStars[3] = "Rigel"; brightStars[4] = "Vega"; for (var count = 0; count < brightStars.length; ++count) { document.write(brightStars[count] + " "); } for Statements (cont)

50 for (var count = 1; count <= 5; ++count) { if (count == 3) continue; document.write(" " + count + " "); } Using CONTINUE Statements to Restart Execution (cont’d.)

51 for (var count = 1; count <= 5; ++count) { if (count == 3) break; document.write(" " + count + " "); } Using CONTINUE Statements to Restart Execution (cont’d.)

Summary An array is a set of data represented by a single variable name A constructor is a special function type used as the basis for creating new objects An array element index identifies the element’s numeric position within the array An array's length property returns the number of elements in an array 52

Summary (cont) Decision making structures are used to determine the order in which statements execute in a program May execute in a linear fashion – if statement and if…else statement – switch statement and case labels – break statement: used to exit control statements 53

Summary (cont) May repeat the same statement, function, or code section Loop statements – while statements, do...while statements, and for statements – Each repetition of a looping statement is called an iteration – A counter variable is a special variable that is incremented or decremented with each iteration of a loop statement – continue statement Restarts a loop with a new iteration 54