Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Arrays and Control Structures CST 200 – JavaScript 2 – 25 - 13."— Presentation transcript:

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

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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

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

14 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

15 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

16 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

17 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 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

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

20 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

21 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

22 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

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

24 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

25 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

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

27 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

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

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

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

32 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”

33 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

34 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

35 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 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 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 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

39 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?

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

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

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

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

44 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

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

46 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

47 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

48 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 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 50 for (var count = 1; count <= 5; ++count) { if (count == 3) continue; document.write(" " + count + " "); } Using CONTINUE Statements to Restart Execution (cont’d.)

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

52 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

53 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

54 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


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

Similar presentations


Ads by Google