1 / 28

M150: Data, Computing and Information

M150: Data, Computing and Information. Unit Seven: An introduction to programming using JavaScript – Part 2. 4- Programming for repetition: the while statement.

lburrows
Télécharger la présentation

M150: Data, Computing and Information

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. M150: Data, Computing and Information Unit Seven: An introduction to programming using JavaScript – Part 2

  2. 4- Programming for repetition: the while statement The while statement (while loop), which has the effect of repeating execution of one or more program statements while a certain condition remains true while (Boolean condition/expression) { one or more statements } The body of the while statement 2

  3. 4- Programming for repetition: the while statement (1) var currentYear, yearOfBirth; (2) var age; // age this year (3) currentYear = 2008; (4) yearOfBirth = window.prompt('Please enter your year of birth','') (5) yearOfBirth = parseFloat(yearOfBirth); (6) while (yearOfBirth < 1900 || yearOfBirth > 2008) (7) { (8) document.write('You must enter a year of birth between 1900 and 2008' + '<BR>'); (9) yearOfBirth = window.prompt('Please enter your year of birth', ''); (10) yearOfBirth = parseFloat(yearOfBirth) (11) }; (12) age = currentYear -yearOfBirth; (13) if (age >= 60) (14) { (15) document.write(‘Free Tax') (16) } (17) else (18) { (19) document.write(‘ Tax is 15%') (20) } Only years of birth between 1900 and 2008 are accepted as valid, and the user is repeatedly prompted until he or she enters a valid year. The initial statements requesting input and converting it into a number (lines (4) and (5)) are repeated inside the loop (as lines (9) and (10)). 3

  4. 4- Programming for repetition: the while statement You need to test the previous program with some valid years – between 1900 and 2008 – and some invalid years (at least one before 1900 and at least one after 2008). The boundary values are 1899, 1900, 1901, 2007, 2008 and 2009. If the Boolean expression controlling a while loop evaluates to true, the whole of the body is executed. Then execution returns to the top of the while statement and the condition is tested again to see if it is still true. If it is, the body is executed again, and so on until the condition evaluates to false. The body of the while statement is then skipped over and execution of the rest of the program continues. 4

  5. 4- Programming for repetition: the while statement Example var password, repeatPassword; password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter your password',''); while (password != repeatPassword) { document.write('Your passwords don\'t match' + '<BR>'); password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter your password', ‘‘); }; You are repeatedly prompted to enter a new password, and then retype it, until the two inputs match. 5

  6. 4- Programming for repetition: the while statement Example (Find the output of the following code) myVar = window.prompt('Enter a number smaller than 30',''); myVar = parseFloat(myVar); while (myVar > 30) { document.write('Please enter a number smaller than 30!') } The program would have displayed the line: Please enter a number smaller than 30! over and over again (will be stuck in a never ending (infinite) loop) To correct the code you would need to include instructions in the body of the loop to read in the new input, assign it to myVar and convert it into a number. myVar = window.prompt('Enter a number smaller than 30',''); myVar = parseFloat(myVar); 6

  7. 4- Programming for repetition: the while statement Sentinel value (stopping value): needs to be terminating value, which indicates to the program that there are no more items (you don’t generally know in advance how many data items there will be) Example var word; word = window.prompt('Please enter your first word',''); while (word != 'halt') { document.write(word + ' '); word = window.prompt('Please enter next word or halt to end',''); }; document.write('<BR>' + 'Thank you') The program reads in each word, until it comes to the sentinel value, which is the string 'halt'. Display each input string followed by a space Thank you halt is the sentinel value If you input: halt; the output will be: Hello! nice to meet you Thank you 7 If you input: Hello!, nice, to, meet, you, halt; the output will be:

  8. 4- Programming for repetition: the while statement (1) var total, nextNumber; (2) total = 0; (3) document.write('The current value of the total is ' + total + '<BR>'); (4) nextNumber = window.prompt('Please enter a positive number, any negative number to stop',''); (5) nextNumber = parseFloat(nextNumber); (6) while (nextNumber >= 0) (7) { (8) document.write('Adding the new value of ' + nextNumber + '<BR>'); (9) total = total + nextNumber; (10) document.write('The current value of the total is ' + total + '<BR>'); (11) nextNumber = window.prompt('Please enter a positive number, any negative number to stop',''); (12) nextNumber = parseFloat(nextNumber) (13) }; (14) document.write('The total sum of your numbers is ' + total) The program adds up a succession of positive numbers entered by the user. It displays the total when a negative number is entered. 8

  9. 4- Programming for repetition: the while statement The current value of the total is 0 Adding the new value of 3 The current value of the total is 3 Adding the new value of 6 The current value of the total is 9 Adding the new value of 4 The current value of the total is 13 The total sum of your numbers is 13 If the inputs are: 3, 6, 4, -5; the output will be: The current value of the total is 0 The total sum of your numbers is 0 If you insert // at lines (4) and (5); the output will be: no value is assigned to nextNumber and so, when the condition is tested at line 6, JavaScript cannot compare it with 0, as required. In this situation JavaScript simply returns false. Hence the body of the while loop is skipped 9

  10. 4- Programming for repetition: the while statement Continue: The current value of the total is undefined Adding the new value of 3 The current value of the total is NaN Adding the new value of 6 The current value of the total is NaN The total sum of your numbers is NaN If you insert a comment (//) at line (2) with inputs 3, 6 and -5; the output will be: If line (2), which initialises the variable total, is deleted, the value of total is still undefined when line (3) is execute. When, in line (9), JavaScript tries to add a new value to this undefined variable, the current value of total is displayed as above 10

  11. 4- Programming for repetition: the while statement Example var product, nextNumber; product = 1; document.write('The current value of the product is '+ product + '<BR>'); nextNumber = window.prompt('Please enter a positive number, 0 to stop',''); nextNumber = parseFloat(nextNumber); while (nextNumber != 0) { document.write('Multiplying by ' + nextNumber + '<BR>'); product = product * nextNumber; document.write('The current value of the product is ' + product + '<BR>'); nextNumber = window.prompt('Please enter a positive number, 0 to stop',''); nextNumber = parseFloat(nextNumber) }; document.write('The product of your numbers is ' + product) The program multiplies together all the positive numbers you input, stopping when the sentinel 0 is input Initializing product to 0 wouldn’t work as 0 multiplied by any other number will always give 0. It must be initialized by 1 11

  12. 4- Programming for repetition: the while statement String In JavaScript, strings are object types They have a number of methods associated with them. charAt() method: (stringName.charAt(n) ) will return the character in the position after n in the string stringName. The characters in a JavaScript string are numbered (indexed) from 0 to one less than the number of characters. So stringName.charAt(0) returns the character that is the first in the string (starting from the left); stringName.charAt(4) returns the character in the fifth position from the left. 12

  13. 4- Programming for repetition: the while statement Example var myString; myString = window.prompt('Please enter a string with exactly 5 characters',''); document.write('You have chosen the following word ‘+myString + '<BR>'); document.write('The character in the first position is ' + myString.charAt(0) + '<BR>'); document.write('The character in the fifth position is ' + myString.charAt(4) + '<BR>') The output of the following statement if you input ‘hello’ is: document.write('The character in the last position is ' + myString.charAt(5)+ '<BR>') You have chosen the following word hello The character in the first position is h The character in the fifth position is o If you input ‘hello’; the output will be: The character in the first position is No character in the sixth position 13

  14. 4- Programming for repetition: the while statement Example var myWord, index; myWord = window.prompt('Please enter a word which has an e init',''); index = 0; while (myWord.charAt(index) != 'e') { index=index+1 }; document.write('The first occurrence of letter e is in position ' + (index + 1) + ' in ' + myWord) a program which searches a word for a particular letter, in this case e, and writes out its position in the string. The first occurrence of letter e is in position 2 in tea If the input is tea, the output will be 14

  15. 5- Programming for repetition: the for statement Syntax of a for loop for (declare and initialize counter; test value of counter; change value of counter) { statement (s) } 15

  16. 5- Programming for repetition: the for statement for statement (for loop) Repeat the execution of a block of statements a predetermined number of times The for statement is controlled by a counter, and can be used only when the number of repetitions is known before execution of the statement To use a JavaScript for loop, you need to know: the starting value of the counter; the final value of the counter for which the loop body is executed; the fixed number by which the counter is increased or decreased after each repetition; the statement (s) which make up the body of the loop (as for a while loop). 16

  17. 5- Programming for repetition: the for statement The code writes out the value of count, and then increases it by 1. It does this 10 times. Count is 1 Count is2 Count is3 Count is4 Count is5 Count is6 Count is7 Count is8 Count is9 Count is10 Thank you The final value of count is 11 The output will be: 17

  18. 5- Programming for repetition: the for statement Example: initialValue = window.prompt('Please enter an initial value for count',''); initialValue = parseFloat(initialValue); endValue = window.prompt('Please enter a stopping value for count',''); endValue = parseFloat(endValue); stepValue = window.prompt('Please enter a step value',''); stepValue = parseFloat(stepValue); for (var count = initialValue; count <= endValue; count = count +stepValue) { document.write('Count is ' + count + '<BR>') }; document.write('Thank you'+ '<BR>') The program writes out the value of count in increasing order. The initial value, the end value and the step will be entered by the user Count is 3 Count is 5 Count is 7 Count is 9 Thank you If the inputs are: 3, 9, 2; the output will be: 18

  19. 5- Programming for repetition: the for statement About the previous example: If you enter an initial value which is greater than the final value, then the condition will evaluate to false the first time it is tested, so the body of the loop will never be evaluated and the value of count will never be displayed. You can change the previous program to writes out the value of count in descending order by replace the for statement as follows: for(var count = initialValue; count >= endValue; count = count - stepValue) (the comparison operator has been changed from <= to >= and the counter is decremented rather than incremented). Count is 9 Count is 7 Count is 5 Count is 3 Thank you After replace the previous statement; If the inputs are: 9, 3, 2; the output will be: 19

  20. 5- Programming for repetition: the for statement Example: for (var count = 1; count <= 6; count = count + 1) { document.write('*') }; document.write('I\'ve finished!') The counter is only initialized once regardless of the number of iteration The condition will need to evaluate to true six times; on the seventh attempt it will evaluate to false ****** I’ve finished The output is: 20

  21. 5- Programming for repetition: the for statement Example var length; var character; length = window.prompt('Please enter the length of your line',''); length = parseFloat(length); character = window.prompt('Please enter your chosen character',''); for (var count = 1; count <= length; count = count + 1) { document.write(character + ’<BR>’) } In this program, the user will enter the length of the character (line), and the character to be output + + + If you input 3, + ; the output will be: 21

  22. 5- Programming for repetition: the for statement Example: var total; // total of scores so far var score; // score for a single student var average; // average score total = 0; /* insert code for a for loop to read in and add the 5 scores to total */ for (var count = 1; count <= 5; count = count + 1) { score = window.prompt('please enter next score',''); score = parseFloat(score); total = total + score }; average = total / 5; document.write('average score is ' + average + '<BR>') In this program, the user is prompted to enter a score and this score is added to the total (average exam score) 22

  23. 5- Programming for repetition: the for statement Convert the for statement to while statement It is always possible to write a while loop that is equivalent to for loop, but we recommend that when you know how many iterations are required you use a for loop. It is not usually possible to write a for loop that is equivalent to a while loop, because while loops are normally used where you don’t know in advance how many iterations will be required 23

  24. 5- Programming for repetition: the for statement More about String String objects are associated with: methods (behaviors) as charAt() properties, which hold information related to their structure and state (value). String objects have one such property called length which, holds the number of characters in the string StringName.length: ‘dot’ notation is used to indicate a property associated with an object Note: The index of the last character in the string is the length of the string minus 1. lastIndex = StringName.length – 1 24

  25. 5- Programming for repetition: the for statement Example var myString; // string entered by user // initialise myString to an empty string myString = ''; while (myString != 'end') { myString = window.prompt('Please input a string; enter end to finish',''); document.write('The length of ' + myString + ' is ' + myString.length + '<BR>') }; The program repeatedly prompts the user to enter a string, and displays its length until the user enters a terminating string, end. If the input is the output will be hello The length of hello is 5 (empty string) The length of is 0 ****** The length of ****** is 6 hello world The length ofhello worldis 11 123456789 The length of 123456789 is9 end The length ofend is 3 25

  26. 5- Programming for repetition: the for statement Example: var myString; myString = window.prompt('Please enter a string',''); //Remember -the arguments to charAt() start at 0, not 1 for (var count = 0; count < myString.length; count = count + 1) { document.write(myString.charAt(count) + '*') } Control structure: is control the flow of execution of the program (the order in which statements are executed). Such as if statement, while statements and for statements Flow of control: is the flow of execution, which is dependent on the evaluation of Boolean conditions The program reads a string from the user and outputs the characters, each followed by an asterisk. For example, if the user inputs the string hello, the output will be: h*e*l*l*o* 26

  27. 5- Programming for repetition: the for statement Example: var myString; var word, letter; word = window.prompt('Please enter a word',''); for (var count = 0; count < word.length; count = count + 1) { letter = word.charAt(count); if (letter == 'e') { document.write('*') } else { document.write(letter) }; } The program reads in a word from the user, and displays it with any occurrences of the letter e replaced by asterisks 27

  28. 5- Programming for repetition: the for statement Example: var word, total; word = window.prompt('please enter a word',''); total = 0; for (var count = 0; count < word.length; count = count + 1) { if (word.charAt(count) == 'e') { total = total + 1 } }; document.write('The number of occurrences of e in the word ' +word + 'is'+ total) The program displays the number of occurrences of the letter e in the input word 28

More Related