arrays and control structures cst 200 – javascript 2 – 25 - 13

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

Upload: malcolm-gary-morton

Post on 26-Dec-2015

232 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

Arrays and Control Structures

CST 200 – JavaScript2 – 25 - 13

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

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

Page 3: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

Storing Data in Arrays • So far, we have seen how to declare and use

variables to store single pieces of informationvar 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

Page 4: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 5: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

Declaring and Initializing Arrays (cont)• Examples:

– Create an array named cellPhonesvar cellPhones = new Array();

– Create an array named cellPhones having 10 elementsvar cellPhones = new Array(10);

• Index– Element’s numeric position within the array– Array element numbering

• Starts with index number of zero (0)

5

Page 6: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

Declaring and Initializing Arrays (cont)• Example:

Create an array named cellPhones having 10 elementsvar cellPhones = new Array(10);

6

keyword new Array( ) constructor

Number of elements to be stored in array

Page 7: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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 elementcellPhones[1] = "LG VX8360"; // second elementcellPhones[2] = "Motorola MOTO W755"; // third element

Notice: the first array element has the index 0

Page 8: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 9: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 10: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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 typeExample:var myData = new Array();myData[0] = "Seth"; // string valuemyData[1] = 89; // numeric valuemyData[2] = true; // boolean value

10

Page 11: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 12: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

Determining the Number of Elements in an Array

• The Array class has a length property that stores the number of elements in an array

• Syntaxarray_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

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

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

Page 14: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 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 myFriendsii. Assign a string value of your friends name to the first

array element (ex: "Jim Perkins" )

iii. Assign another friend to the second array elementiv. Assign another friend to the third array element

14

Page 15: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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 questionsii. 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 elementiv. Use the document.write( ) method to output the second

array element valuev. Use the window.alert( ) method to output the first array

element value

15

Page 16: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 17: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

if Statements

• Used to execute specific programming code if conditional expression evaluates to true

• Syntaxif (conditional expression)

statement;

• After the if statement executes:– Any subsequent code executes normally

17

Page 18: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 19: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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;}

Page 20: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 21: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 22: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 23: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

if...else Statements (cont)

• Example:

23

var today = "Tuesday"if (today == "Monday") document.write("Today is Monday");else document.write("Today is not Monday");

Page 24: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

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

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

Page 26: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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."); }}

Page 27: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 28: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

switch Statements (cont)

• Syntax

28

switch (expression) {case label:

statement(s);case label:

statement(s);. . .default:

statement(s);}

Page 29: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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");}

Page 30: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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 Edition 30

Page 31: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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)

Page 32: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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”

Page 33: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 34: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

while Statements

• while statement repeats a statement or series of statements as long as a given conditional expression evaluates to true

• Syntaxwhile (conditional expression) {

statement(s);}

• Each repetition of a looping statement is called an iteration

34

Page 35: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 36: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

36

var x = 1;while ( x <= 5) {

document.write( x + "<br />");++x;

}document.write("<p>You have printed 5 numbers.</p>");

while Statements (cont)

Note the special ++ increment operator

++ increment operator adds 1 to the variable

Page 37: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

37

var count = 10;while (count > 0) {

document.write(count + "<br />");--count;

}document.write("<p>We have liftoff.</p>");

while Statements (cont)

Note the special -- decrement operator

-- decrement operator subtracts 1 from the

variable

Page 38: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

38

var count = 1;while (count <= 100) {

document.write(count + "<br />");count *= 2;

}

while Statements (cont)

Note the special *= multiplication assignment

operator

count *= 2 is the same as

count = count * 2

Page 39: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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?

Page 40: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

while Review• Practice writing a while statement:• Write a while statement that displays the

numbers 1 through 50

40

Page 41: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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);

Page 42: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

do...while Statements (cont)

• Example:

42

var count = 0;do {

document.write("The count is: " + count );++count;

} while (count < 5);

Page 43: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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);

}

Page 44: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

for Statements (cont)• The steps the JavaScript interpreter performs

when it encounters a for loop1. Declare and initialize counter variable2. Evaluate for loop condition3. 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

Page 45: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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] + "<br />");}

Page 46: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 47: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 48: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 49: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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] + "<br />");}

for Statements (cont)

Page 50: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

50

for (var count = 1; count <= 5; ++count) {if (count == 3)

continue;document.write("<p>" + count + "</p>");

}

Using CONTINUE Statements to Restart Execution (cont’d.)

Page 51: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

51

for (var count = 1; count <= 5; ++count) {if (count == 3)

break;document.write("<p>" + count + "</p>");

}

Using CONTINUE Statements to Restart Execution (cont’d.)

Page 52: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 53: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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

Page 54: Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13

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