1 / 54

Arrays and Control Structures

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

vaughan
Download Presentation

Arrays and Control Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

  3. Storing Data in Arrays • So far, we have seen how to declare and use variables to store single pieces of information varcellPhone = "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

  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 vararrayName= newArray(number of elements);

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

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

  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 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 varcellPhones = new Array(); cellPhones[0] = "BlackBerry Storm 9530"; cellPhones[1] = "LG VX8360";

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

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

  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] ); 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: varshopList = new Array( ); shopList[0] = "eggs"; shopList[1] = "bread"; shopList[2] = "cheese"; shopList[3] = "apple juice"; document.write("shopList array size: " + shopList.length );

  13. Exercise – Web Console • Use Web Console to type the following statements and expressions (one at a time, press Enter after each): varfavCities = 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;

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

  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: • Declare an array called questions • Assign a string value of a question into the first array element (ex: "What is your name?" ) • Assign another question to the second array element • Use the document.write( ) method to output the second array element value • Use the window.alert( ) method to output the first array element value

  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 forstatements to make decisions and modify control flow

  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

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

  19. if...else Statements (cont) • Can use command blocks to specify multiple statements should be executed within if...else statement • Syntax 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 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"

  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;

  23. if...else Statements (cont) • Example: 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"

  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

  26. Nested if and if...else Statements (cont) • Example: 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

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

  29. switch Statements (cont) • Example: varage= 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 Edition

  31. switch Statements (cont) functioncity_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"; } }

  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:

  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...whilestatements • for statements

  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

  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

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

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

  38. while Statements (cont) var count = 1; while (count <= 100) { document.write(count + "<br />"); count *= 2; } 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): 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

  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 • do { • statement(s); • } while (conditional expression);

  42. do...while Statements (cont) • Example: 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 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

  45. for Statements (cont’d.) • Example: vardaysOfWeek = 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 />"); }

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

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

  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

  49. for Statements (cont) varbrightStars = 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 />"); }

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

More Related