The syntax of a while loop - Temple MIS

The syntax of a while loop - Temple MIS

Programming Control Structures MIS 3406 Department of MIS Fox School of Business Temple University The syntax of a while loop while ( condition ) { statements } A while loop that adds the numbers from 1 through 5

var sumOfNumbers = 0; var numberOfLoops = 5; var counter = 1; while (counter <= numberOfLoops) { sumOfNumbers += counter; // adds counter to sumOfNumbers counter++; // adds 1 to counter } alert(sumOfNumbers); // displays 15

Another way of doing the calculations sumOfNumbers = sumOfNumbers + counter; // add counter to sumOfNumbers counter = counter + 1; // add one to counter 2 The syntax of a do-while loop do { statements } while ( condition ); A do-while loop that adds the numbers

from 1 through 5 var sumOfNumbers = 0; var numberOfLoops = 5; var counter = 1; do { sumOfNumbers += counter; // adds counter to sumOfNumbers counter++; // adds 1 to counter } while (counter <= numberOfLoops);

alert(sumOfNumbers); // displays 15 3 Another do-while loop example do { var investment = prompt("Enter investment amount as xxxxx.xx", 10000); investment = parseFloat(investment); if ( isNaN(investment) ) {

alert("Investment must be a number"); } } while ( isNaN(investment) ); DISCUSS what, in your own words, is this code saying? If you wanted to describe these 9 lines of code with a comment, what would the comment be? 4

The syntax of a for loop for (counter initialization; condition; increment expression ) { statements } A for loop that adds the numbers from 1 through 5 var sumOfNumbers = 0; var numberOfLoops = 5; for ( var counter = 1; counter <= numberOfLoops; counter++ ) { sumOfNumbers += counter;

} alert(sumOfNumbers); 5 Another example of a for loop var var var var for

investment = 10000; annualRate = 7.0; years = 10; futureValue = investment; ( var i = 1; i <= years; i++ ) { futureValue += futureValue * annualRate / 100; } alert (futureValue);

// displays 19672 Other ways that the future value calculation could be coded futureValue = futureValue + (futureValue * annualRate / 100); futureValue = futureValue * (1 + (annualRate / 100)) Lets see some loops at work! (see rocket.zip) 6

What is an array? An array is a data type that can contain one or more items called elements. Each element stores a value that you can refer to with an index. The length of the array indicates the number of elements that it contains. In short, an array is a structure that allows us to store multiple pieces of similar data. The syntax for creating an array Two ways to create an array in J avaScript Using the new keyword with the Array object name

var arrayName = new Array(length); Using an array literal var arrayName = []; Example: a statement that creates an array var totals = []; 8 How to add values to an array

totals[0] = 141.95; totals[1] = 212.25; totals[2] = 411; This number, inside the square brackets, is the index to the array. It indicates what piece of the array we are going to add a value to. QUESTION: What is the index of the first value in the above array? Careful! JavaScript arrays are zero-based and that is often a source of trouble for first-time coders. Now that the totals array exist, and some values have been assigned to it, I can use totals[2], totals[1] and totals[0] like any other primitive variable.

9 How big is the array? J avaScript arrays have a length property arrayName.length QUESTION: Using the totals array from the last slide, what number would this command display? alert(totals.length); A statement that gets the length of an array var count = totals.length; //put the size of the array //in a variable named count

How to add a value to the end of an array totals[totals.length] = 135.75; 10 Putting arrays to work Put numbers 1 through 10 into an array var numbers = []; for (var i = 0; i < 10; i++) { numbers[i] = i + 1;

} Code that displays the numbers in the array var numbersString = ""; for (var i = 0; i < numbers.length; i++) { numbersString += numbers[i] + " "; } alert (numbersString); The message thats displayed

11 Putting arrays to work(2) Code that puts four values into an array var totals = []; totals[0] = 141.95; totals[1] = 212.25; totals[2] = 411; totals[3] = 135.75; Code that sums the values in the array

var sum = 0; for (var i = 0; i < totals.length; i++) { sum += totals[i]; } // whats next? QUESTION: Using the JavaScript covered in this lecture, what one line of code here could you add after whats next that would alert the user and display the average of totals? 12

Code that displays the totals and the sum // assuming that totals array already exists var totalsString = ""; for (var i = 0; i < totals.length; i++) { totalsString += totals[i] + "\n"; } alert ("The totals are:\n" + totalsString + "\n" + "Sum: " + sum); The message thats displayed

13 GuessANumber.js (cont.) Update GuessANumber.js so that the program loops while the guess does not match the randomly generated number. Each time through the loop the program will tell the user if their latest guess was too high or too low. The program will also keep track of how many total guesses the user made before they guessed the actual number. Once they guess the correct number, the program will display an appropriate message including how many guesses they made. 14

BugCollector.js A bug collector collects bugs every day for five days. Write a program that keeps a running total of the number of bugs collected during the five days. The loop should ask for the number of bugs collected for each day, and when the loop is finished, the program should display the total number of bugs collected. CaloriesBurned.js Running on a particular treadmill you burn 4.2 calories per minute. Write a program that uses a loop to display the number of calories burned after 10, 15, 20, 25, and 30 minutes.

BudgetAnalysis.js Write a program that asks the user to enter the amount that he or she has budgeted for a month. A loop should then prompt the user to enter each of his or her expenses for the month and keep a running total. When the loop finishes, the program should display the amount that the user is over or under budget. DistanceTraveled.js The distance a vehicle travels can be calculated as follows: distance=speedtime For example, if a train travels 40 miles per hour for three hours, the distance traveled is 120 miles. Write a program that asks the user for the speed of a vehicle (in miles per hour) and the

number of hours it has traveled. It should then use a loop to display the distance the vehicle has traveled for each hour of that time period. AverageRainfall.js Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.

C2FTable.js Write a program that displays a table of the Celsius temperatures 0 through 20 and their Fahrenheit equivalents. The formula for converting a temperature from Celsius to Fahrenheit is F=(9/5)C+32 where F is the Fahrenheit temperature, and C is the Celsius temperature. Your program must use a loop to display the table. PenniesForPay.js Write a program that calculates the amount of money a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table

showing what the salary was for each day, then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies. SumOfNumbers.js Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum. OceanLevels.js Assuming the oceans level is currently rising at about 1.6 millimeters per year, create an application that displays the number of millimeters that the ocean will have risen each year

for the next 25 years. TuitionIncrease.js At one college, the tuition for a full-time student is $8,000 per semester. It has been announced that the tuition will increase by 3 percent each year for the next 5 years. Write a program with a loop that displays the projected semester tuition amount for the next 5 years. WeightLoss.js If a moderately active person cuts their calorie intake by 500 calories a day, they can typically lose about 4 pounds a month. Write a program that lets the user enter their starting weight, then creates and displays a table showing what their expected weight will be at the end of

each month for the next 6 months if they stay on this diet. Factorial.js In mathematics, the notation n! represents the factorial of the nonnegative integer n. The factorial of n is the product of all the nonnegative integers from 1 to n. For example, 7!=1234567=5,040 and 4!=1234=24 Write a program that lets the user enter a nonnegative integer then uses a loop to calculate the factorial of that number. Display the factorial.

Population.js Write a program that predicts the approximate size of a population of organisms. The application should allow the user to enter the starting number of organisms, the average daily population increase (as a percentage), and the number of days the organisms will be left to multiply. For example, assume the user enters the following values: Starting number of organisms: 2 Average daily increase: 30% Number of days to multiply: 10

Pattern1.js Write a program that uses nested loops to draw the following pattern: Pattern2.js Write a program that uses nested loops to draw the following pattern:

Recently Viewed Presentations

  • Youth Ministry Risk Management

    Youth Ministry Risk Management

    CMI Risk Management. Prepared ByChristian Ministries InsurancePO Box 367Welches, Oregon 97367503.622.3255www cmirisk.comBob Lilly COO - LaPorte & AssociatesScott Stuart - Owner Christian Ministries Ins
  • System Analysis of Clinical Incidents The London Protocol

    System Analysis of Clinical Incidents The London Protocol

    The London Protocol Background While it is sometimes straightforward to identify a particular action or omission as the immediate cause of an incident, closer analysis usually reveals a series of events leading up to an adverse outcome. The identification of...
  • Mark Walters, State Director and Al Javois, Chair,

    Mark Walters, State Director and Al Javois, Chair,

    Previous funding support had not be activated. A tsunami ad hoc committee had been formed on the island of St. Croix as a pilot project with the following sub-committees: Communications Warning Committee Education and Outreach Committee Field reconnaissance at potential...
  • Unconscious Bias in Clinical Care and Medical Education

    Unconscious Bias in Clinical Care and Medical Education

    Definition. Implicit or unconscious bias happens by our brains making incredibly quick judgments and assessments of people and situations without us realizing.Our biases are influenced by our background, cultural environment and personal experiences.We may not even be aware of these...
  • 1 Midwest Mfg/Pro User Group Click to edit

    1 Midwest Mfg/Pro User Group Click to edit

    The study of folklore is sometimes called folkloristics, and people who study folklore are sometimes referred to as "folklorists". The English antiquarian William Thoms introduced the word "folklore" in a letter published in the London journal The Athenaeum in 1846....
  • 1.1 Safety in the Science Classroom

    1.1 Safety in the Science Classroom

    See page 185 Concave Mirrors The image formed by a concave mirror depends on the location of the object (see A, B, C). Flashlights, car headlights, and telescopes, are a few applications of concave mirrors. (c) McGraw Hill Ryerson 2007...
  • Vet Science ID - usd306.k12.ks.us

    Vet Science ID - usd306.k12.ks.us

    Vet Science ID. TOOLS. Autoclave. Bands (Castration or docking) Centrifuge. Comb-Curry. Comb-flea. Comb-Scotch. Cover slips. Dehorner- Barnes. Dehorner- electronic. Dehorner- scoop or tube. ... Scissors- Littauer Suture removal. Scissors- Mayo Disecting. Scissors MetzenbaumDisecting.
  • Foreign Trade & The NEI   Industry Requirements for

    Foreign Trade & The NEI Industry Requirements for

    Kudos to Administration for TPP effort (Ensure transparent, science-based and least trade restrictive. First time: goal is harmonize lab certification approaches. ... AD/CVD. 2002 - Can't call it "catfish" - Bassa. 2008 - solve this - "catfish" subject to grading...