SlideShare una empresa de Scribd logo
1 de 35
Unit 8 Programs and Data
Arrays tmaScoreArray Index values array elements 89 4 78 3 82 5 85 2 87 1 92 0
Referencing Array Elements tmaScoreArray tmaScoreArray[0] tmaScoreArray[3] 89 4 78 3 82 5 85 2 87 1 92 0
Array Declaration and Initialisation var  tmaScoreArray =  new  Array(6); // value of all array elements will be undefined until initialised // initialisation of array elements tmaScoreArray[0] = 92; tmaScoreArray[1] = 87; tmaScoreArray[2] = 85; tmaScoreArray[3] = 78; tmaScoreArray[4] = 89; tmaScoreArray[5] = 82; var  tmaScoreArray = [92,87,85,78,89,82]; 1 2
Referencing Array Elements ? 4 ? 3 ? 5 ? 2 ? 1 ? 0 tmaScoreArray[0] = 92; 92 87 tmaScoreArray[1] = 87; tmaScoreArray[2] = 85; 85 tmaScoreArray[3] = 78; 78 tmaScoreArray[4] = 89; 89 tmaScoreArray[5] = 82; 82 var  tmaScoreArray =  new  Array(6);
Accessing Array Elements var  tmaScoreArray = [92,87,85,78,89,82]; var  tma1; tma1 = tmaScoreArray[0]; document.write('Your score for TMA01 was: '  + tma1]); Your score for TMA01 was: 92  The output is the same for both methods var  tmaScoreArray = [92,87,85,78,89,82]; document.write( '  Your score for TMA01 was: ' + tmaScoreArray[0]); 1. Assigning value in array element to a variable 2. Accessing value in array element directly
The length Property var  studentArray = [‘David’,’Nicky’,’Mike’,’Carl’,’Eda’,’Ian’]; index 0 to 5 The length of the array is 6 (one more than the  index of the last element). ‘ Eda’ 4 ‘ Carl’ 3 ‘ Ian’ 5 ‘ Mike’ 2 ‘ Nicky’ 1 ‘ David’ 0
More on the length property var  studentArray =  [‘David’,’Nicky’,’Mike’,’Carl’,’Eda’,’Ian’]; var  studentArray = [,,,,,]; var  studentArray =  new  Array(6); Whether you:  declare and initialise an array with six elements, or  declare an array with six empty elements, or  declare a new array with six elements not yet initialised, they all have length 6. If this array was half full it would still have length 6.
Using the length Property var  studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; document.write('Array length is: ' + studentArray.length); document.write('<br>The last element is: ' + studentArray[studentArray.length - 1]); Array length is: 6 The last element is: Ian  Output
Structured English for each student name in the array write out the name end for
Processing Arrays var  studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; //Write out list of students for  ( var  i = 0; i < studentArray.length; i = i + 1) { document.write(studentArray[i] + '<br>') } David Nicky Mike Carl Eda Ian  Output
Joining Output from Two Arrays var  studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var  surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; //Write a list of first names and surnames of students for  ( var  i = 0; i < studentArray.length; i = i + 1) { document.write(studentArray[i] + ' '  + surnameArray[i] + '<br>'); }
Output David Gates Nicky Lovelace Mike Pascal Carl Babbage Eda Hopper Ian von Neumann
Combining Two Arrays var  studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var  surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; var  fullNameArray =  new  Array(6); //Join first names and surnames in third array and write out for  ( var  i = 0; i < fullNameArray.length; i = i + 1) { fullNameArray[i] =  studentArray[i] + ' ' + surnameArray[i];  document.write(fullNameArray[i] + '<br>') }
Don't know the number of students? Prompt for input! var  numberOfStudents;  var  markArray;  numberOfStudents = parseFloat(window.prompt('How many students do you have?', '')); markArray =  new  Array(numberOfStudents); for  ( var  student = 0; student < numberOfStudents;  student = student + 1)  {  markArray[student] =  window.prompt('Enter student mark', '')  }
Making it more informative var  studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var  surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; var  fullNameArray =  new  Array(6); document.write ('Array program to display numbered students<br><br>'); //Join first names and surnames in third array and write out for  ( var  i = 0; i < fullNameArray.length; i = i + 1) { fullNameArray[i] =  studentArray[i] + ' ' + surnameArray[i];  document.write( 'Student ' + (i + 1) + ': ' +   fullNameArray[i] + '<br>') } document.write('<br>End of display');
Output Array program to display numbered students Student 1: David Gates Student 2: Nicky Lovelace Student 3: Mike Pascal Student 4: Carl Babbage Student 5: Eda Hopper Student 6: Ian von Neumann End of display
Finding the Maximum Value initialise array of TV hours watched for 7 days initialise maximum TV hours watched to hours in day 1 for each day of the week except the first compare the hours with the current maximum if it is bigger replace current maximum with that days hours end for write out the final maximum number of hours
Finding the Maximum Value var  tvHoursArray = [5,3,4,2,6,1]; var  maxTvHours = tvHoursArray[0];  for ( var  day = 1; day < tvHoursArray.length;  day = day + 1) { if(tvHoursArray[day] > maxTvHours) { maxTvHours = tvHoursArray[day] } } document.write('Maximun hours of TV watched was: ' + maxTvHours); Maximun hours of TV watched was: 6  Output
Improving the Output var  tvHoursArray = [5,3,4,2,6,1]; var  maxIndex = 0; for ( var  day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] >  tvHoursArray[maxIndex] ) { maxIndex = day } } document.write('Maximun hours of TV watched was: ' + tvHoursArray[maxIndex] + ' on day ' + (maxIndex + 1)); Maximun hours of TV watched was: 6 on day 5  Output
Improving the Output var  tvHoursArray = [5,3,4,2,6,1]; var  maxTvHours = tvHoursArray[0]; //Initialise to 1st element in array var   maxIndex = 0; for ( var  day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > maxTvHours) { maxTvHours = tvHoursArray[day] ; maxIndex = day } } document.write('Maximun hours of TV watched was: ' + maxTvHours  + ' on day ' + (maxIndex + 1) ); Maximun   hours of TV watched was: 6 on day 5  Output
Math.round() document.write(Math.round(12.2638631)); document.write('<br>'); document.write(Math.round(12.7128452)) 12 13  Output
Functions function  doSomething() { //some statements  } Syntax function  sayHello() { document.write('Hello!')  } Example Header Body
Functions function  sayHello() { document.write('Hello!')  } // Call  or  invoke  the funtion sayHello() sayHello(); /*  Call  or  invoke  the function  sayHelloSomebody(name) */ sayHelloSomebody('Rita') function  sayHelloSomebody(name) { document.write('Hello! ' + name)  } Hello! Output Hello! Rita Output
<HTML> <HEAD> <TITLE>  Greeting Program  </TITLE> <SCRIPT> //Greeting function function  sayHelloSomebody(name) { document.write('Hello! ' + name)  }; var  myName; //Prompt for name and assign to variable myName = window.prompt('Please input your name','Put your name here'); //Call function sayHelloSomebody(myName); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Hello! Rita Output
Functions That Return a Value function  total(numberA, numberB) { return  numberA + numberB } document.write( total(2,3) );  //function call function  total(numberA, numberB) { return  numberA + numberB } var  sum; sum =  total(2,3) ;  //function call document.write(sum); Output 5 Output 5 1 2
Formal and Actual Arguments function  sayHelloSomebody(name) { document.write('Hello! ' + name)  } sayHelloSomebody('Rita') formal argument Actual argument
Command Line  Interface Graphical User  Interface
document.form1.helloButton.value Window Document Form Widgets or  elements
Creating Elements <BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT TYPE = &quot;button&quot;    VALUE = &quot;Try me&quot;  ONCLICK = &quot;document.form.helloBox.value = 'Hello!'&quot;> <!-- Create the textBox --> <INPUT  TYPE = &quot;text&quot;    NAME = &quot;helloBox&quot;    VALUE = ''> </FORM> </BODY>
<BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT TYPE = &quot;button&quot;    VALUE = &quot;Try me&quot;    ONCLICK = &quot;window.alert(What a great tutorial!)'&quot;> </FORM> </BODY>
<BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT  TYPE = &quot;button&quot;  VALUE = &quot;Try me&quot;  ONCLICK = &quot;window.confirm('Do you still love me?')&quot;> </FORM> </BODY>
<BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT  TYPE = &quot;button&quot;  VALUE = &quot;Try me&quot;  ONCLICK =  &quot;document.write(window.confirm('Do you still love me?'))&quot;> </FORM> </BODY> true Output
More About Strings myString myString.length is ? mystring.charAt(5) is ? myString.indexOf('d') is ? index 11 10 9 8 7 6 5 4 3 2 1 0 ! d l r o w o l l e H
/* function to check whether a character is 'a', 'b' or 'c' */ function  isabORc(aChar) { return  (aChar >= 'a') && (aChar <= 'c') }; var  inputChar; inputChar = window.prompt('Please input a character'); if   { document.write('The character was ' + inputChar) } else { document.write('The character was not a, b or c') } (isabORc(inputChar)) //evaluate function call

Más contenido relacionado

La actualidad más candente

The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202Mahmoud Samir Fayed
 
Implementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingImplementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingVincent Pradeilles
 
Python for Data Science and Scientific Computing
Python for Data Science and Scientific ComputingPython for Data Science and Scientific Computing
Python for Data Science and Scientific ComputingAbhijit Kar Gupta
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleChristopher Curtin
 
The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210Mahmoud Samir Fayed
 
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...BAINIDA
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT IIIMinu Rajasekaran
 

La actualidad más candente (20)

Heap sort
Heap sortHeap sort
Heap sort
 
The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189
 
P4 2017 io
P4 2017 ioP4 2017 io
P4 2017 io
 
XTW_Import
XTW_ImportXTW_Import
XTW_Import
 
Python - Lecture 4
Python - Lecture 4Python - Lecture 4
Python - Lecture 4
 
The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Implementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingImplementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional Programing
 
Heaps
HeapsHeaps
Heaps
 
Python for Data Science and Scientific Computing
Python for Data Science and Scientific ComputingPython for Data Science and Scientific Computing
Python for Data Science and Scientific Computing
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
Heaps
HeapsHeaps
Heaps
 
The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181
 
Collection
CollectionCollection
Collection
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210
 
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT III
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 

Similar a Unit8

Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XMLguest2556de
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteGiordano Scalzo
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript PrimerAdam Hepton
 
Perl Teach-In (part 1)
Perl Teach-In (part 1)Perl Teach-In (part 1)
Perl Teach-In (part 1)Dave Cross
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
ES6 Simplified
ES6 SimplifiedES6 Simplified
ES6 SimplifiedCarlos Ble
 
Introducere In Java Jx
Introducere In Java JxIntroducere In Java Jx
Introducere In Java Jxdanielnastase
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxJumanneChiyanda
 
check the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfcheck the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfangelfragranc
 

Similar a Unit8 (20)

Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infinite
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
 
Perl Teach-In (part 1)
Perl Teach-In (part 1)Perl Teach-In (part 1)
Perl Teach-In (part 1)
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
ES6 Simplified
ES6 SimplifiedES6 Simplified
ES6 Simplified
 
Introducere In Java Jx
Introducere In Java JxIntroducere In Java Jx
Introducere In Java Jx
 
C_Arrays.pptx
C_Arrays.pptxC_Arrays.pptx
C_Arrays.pptx
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
check the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfcheck the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdf
 

Unit8

  • 1. Unit 8 Programs and Data
  • 2. Arrays tmaScoreArray Index values array elements 89 4 78 3 82 5 85 2 87 1 92 0
  • 3. Referencing Array Elements tmaScoreArray tmaScoreArray[0] tmaScoreArray[3] 89 4 78 3 82 5 85 2 87 1 92 0
  • 4. Array Declaration and Initialisation var tmaScoreArray = new Array(6); // value of all array elements will be undefined until initialised // initialisation of array elements tmaScoreArray[0] = 92; tmaScoreArray[1] = 87; tmaScoreArray[2] = 85; tmaScoreArray[3] = 78; tmaScoreArray[4] = 89; tmaScoreArray[5] = 82; var tmaScoreArray = [92,87,85,78,89,82]; 1 2
  • 5. Referencing Array Elements ? 4 ? 3 ? 5 ? 2 ? 1 ? 0 tmaScoreArray[0] = 92; 92 87 tmaScoreArray[1] = 87; tmaScoreArray[2] = 85; 85 tmaScoreArray[3] = 78; 78 tmaScoreArray[4] = 89; 89 tmaScoreArray[5] = 82; 82 var tmaScoreArray = new Array(6);
  • 6. Accessing Array Elements var tmaScoreArray = [92,87,85,78,89,82]; var tma1; tma1 = tmaScoreArray[0]; document.write('Your score for TMA01 was: ' + tma1]); Your score for TMA01 was: 92 The output is the same for both methods var tmaScoreArray = [92,87,85,78,89,82]; document.write( ' Your score for TMA01 was: ' + tmaScoreArray[0]); 1. Assigning value in array element to a variable 2. Accessing value in array element directly
  • 7. The length Property var studentArray = [‘David’,’Nicky’,’Mike’,’Carl’,’Eda’,’Ian’]; index 0 to 5 The length of the array is 6 (one more than the index of the last element). ‘ Eda’ 4 ‘ Carl’ 3 ‘ Ian’ 5 ‘ Mike’ 2 ‘ Nicky’ 1 ‘ David’ 0
  • 8. More on the length property var studentArray = [‘David’,’Nicky’,’Mike’,’Carl’,’Eda’,’Ian’]; var studentArray = [,,,,,]; var studentArray = new Array(6); Whether you: declare and initialise an array with six elements, or declare an array with six empty elements, or declare a new array with six elements not yet initialised, they all have length 6. If this array was half full it would still have length 6.
  • 9. Using the length Property var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; document.write('Array length is: ' + studentArray.length); document.write('<br>The last element is: ' + studentArray[studentArray.length - 1]); Array length is: 6 The last element is: Ian Output
  • 10. Structured English for each student name in the array write out the name end for
  • 11. Processing Arrays var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; //Write out list of students for ( var i = 0; i < studentArray.length; i = i + 1) { document.write(studentArray[i] + '<br>') } David Nicky Mike Carl Eda Ian Output
  • 12. Joining Output from Two Arrays var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; //Write a list of first names and surnames of students for ( var i = 0; i < studentArray.length; i = i + 1) { document.write(studentArray[i] + ' ' + surnameArray[i] + '<br>'); }
  • 13. Output David Gates Nicky Lovelace Mike Pascal Carl Babbage Eda Hopper Ian von Neumann
  • 14. Combining Two Arrays var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; var fullNameArray = new Array(6); //Join first names and surnames in third array and write out for ( var i = 0; i < fullNameArray.length; i = i + 1) { fullNameArray[i] = studentArray[i] + ' ' + surnameArray[i]; document.write(fullNameArray[i] + '<br>') }
  • 15. Don't know the number of students? Prompt for input! var numberOfStudents; var markArray; numberOfStudents = parseFloat(window.prompt('How many students do you have?', '')); markArray = new Array(numberOfStudents); for ( var student = 0; student < numberOfStudents; student = student + 1) { markArray[student] = window.prompt('Enter student mark', '') }
  • 16. Making it more informative var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; var fullNameArray = new Array(6); document.write ('Array program to display numbered students<br><br>'); //Join first names and surnames in third array and write out for ( var i = 0; i < fullNameArray.length; i = i + 1) { fullNameArray[i] = studentArray[i] + ' ' + surnameArray[i]; document.write( 'Student ' + (i + 1) + ': ' + fullNameArray[i] + '<br>') } document.write('<br>End of display');
  • 17. Output Array program to display numbered students Student 1: David Gates Student 2: Nicky Lovelace Student 3: Mike Pascal Student 4: Carl Babbage Student 5: Eda Hopper Student 6: Ian von Neumann End of display
  • 18. Finding the Maximum Value initialise array of TV hours watched for 7 days initialise maximum TV hours watched to hours in day 1 for each day of the week except the first compare the hours with the current maximum if it is bigger replace current maximum with that days hours end for write out the final maximum number of hours
  • 19. Finding the Maximum Value var tvHoursArray = [5,3,4,2,6,1]; var maxTvHours = tvHoursArray[0]; for ( var day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > maxTvHours) { maxTvHours = tvHoursArray[day] } } document.write('Maximun hours of TV watched was: ' + maxTvHours); Maximun hours of TV watched was: 6 Output
  • 20. Improving the Output var tvHoursArray = [5,3,4,2,6,1]; var maxIndex = 0; for ( var day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > tvHoursArray[maxIndex] ) { maxIndex = day } } document.write('Maximun hours of TV watched was: ' + tvHoursArray[maxIndex] + ' on day ' + (maxIndex + 1)); Maximun hours of TV watched was: 6 on day 5 Output
  • 21. Improving the Output var tvHoursArray = [5,3,4,2,6,1]; var maxTvHours = tvHoursArray[0]; //Initialise to 1st element in array var maxIndex = 0; for ( var day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > maxTvHours) { maxTvHours = tvHoursArray[day] ; maxIndex = day } } document.write('Maximun hours of TV watched was: ' + maxTvHours + ' on day ' + (maxIndex + 1) ); Maximun hours of TV watched was: 6 on day 5 Output
  • 22. Math.round() document.write(Math.round(12.2638631)); document.write('<br>'); document.write(Math.round(12.7128452)) 12 13 Output
  • 23. Functions function doSomething() { //some statements } Syntax function sayHello() { document.write('Hello!') } Example Header Body
  • 24. Functions function sayHello() { document.write('Hello!') } // Call or invoke the funtion sayHello() sayHello(); /* Call or invoke the function sayHelloSomebody(name) */ sayHelloSomebody('Rita') function sayHelloSomebody(name) { document.write('Hello! ' + name) } Hello! Output Hello! Rita Output
  • 25. <HTML> <HEAD> <TITLE> Greeting Program </TITLE> <SCRIPT> //Greeting function function sayHelloSomebody(name) { document.write('Hello! ' + name) }; var myName; //Prompt for name and assign to variable myName = window.prompt('Please input your name','Put your name here'); //Call function sayHelloSomebody(myName); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Hello! Rita Output
  • 26. Functions That Return a Value function total(numberA, numberB) { return numberA + numberB } document.write( total(2,3) ); //function call function total(numberA, numberB) { return numberA + numberB } var sum; sum = total(2,3) ; //function call document.write(sum); Output 5 Output 5 1 2
  • 27. Formal and Actual Arguments function sayHelloSomebody(name) { document.write('Hello! ' + name) } sayHelloSomebody('Rita') formal argument Actual argument
  • 28. Command Line Interface Graphical User Interface
  • 30. Creating Elements <BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT TYPE = &quot;button&quot; VALUE = &quot;Try me&quot; ONCLICK = &quot;document.form.helloBox.value = 'Hello!'&quot;> <!-- Create the textBox --> <INPUT TYPE = &quot;text&quot; NAME = &quot;helloBox&quot; VALUE = ''> </FORM> </BODY>
  • 31. <BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT TYPE = &quot;button&quot; VALUE = &quot;Try me&quot; ONCLICK = &quot;window.alert(What a great tutorial!)'&quot;> </FORM> </BODY>
  • 32. <BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT TYPE = &quot;button&quot; VALUE = &quot;Try me&quot; ONCLICK = &quot;window.confirm('Do you still love me?')&quot;> </FORM> </BODY>
  • 33. <BODY> <!-- Create the form --> <FORM NAME = &quot;form1&quot;> <!-- Create the helloButton --> <INPUT TYPE = &quot;button&quot; VALUE = &quot;Try me&quot; ONCLICK = &quot;document.write(window.confirm('Do you still love me?'))&quot;> </FORM> </BODY> true Output
  • 34. More About Strings myString myString.length is ? mystring.charAt(5) is ? myString.indexOf('d') is ? index 11 10 9 8 7 6 5 4 3 2 1 0 ! d l r o w o l l e H
  • 35. /* function to check whether a character is 'a', 'b' or 'c' */ function isabORc(aChar) { return (aChar >= 'a') && (aChar <= 'c') }; var inputChar; inputChar = window.prompt('Please input a character'); if { document.write('The character was ' + inputChar) } else { document.write('The character was not a, b or c') } (isabORc(inputChar)) //evaluate function call

Notas del editor

  1. Don’t forget to do truth tables and precedence from Unit 6 and tracing a program and programming tips: Comments Skeleton and test line by line – ish Insert write lines at points In Unit 8 we are going to look at arrays as an example of a data structure holding a collection of data that has something in common. The Block 2 Glossary defines a data structure as: a collection of simple data items, e.g. numbers, characters or strings, combined together in a specified way so that they can be manipulated as a single entity. We are also going to introduce functions as a way of dealing with complexity. and as a way of reusing useful bits of code. We’ll introduce event-driven programming and some of the facilities that JavaScript has for building a graphical user interface.
  2. Arrays feature in most programming languages but might have slightly different rules or syntax in different languages. So far we have looked at single-valued data but now we are going to look at collections of values in the form of arrays as an example of a data structure and how when we find a pattern or program that works well we can reuse it for something else. These data are all of the same type – numbers - and are related to each other. They are TMA scores, and, as an array, can be manipulated as a single item or the individual elements can be referred to separately. It is structured data. The indexing of an array is similar to that for strings – starting at zero, so the index of the first element is zero. An array must have a named variable – here it&apos;s tmaScoreArray. Q What is the value of the element in the third position? – 85. Q And what is its index? – 2. An array is an object the Array object (with a capital A – all objects begin with a capital letter) that is built into JavaScript and it has its own properties and methods for processing arrays.
  3. You can access or reference an individual element by using the variable name and the index in square brackets. So the first element will be tmaScoreArray square brackets 0 (tmaScoreArray[0]) and the fourth element will be tmaScoreArray square brackets 3 (tmaScoreArray[3]).
  4. There are two ways to declare and initialise an array. If you know what data is going to go into it you can initialise the array at the same time as you declare it as in 1. You declare a variable such as tmaScoreArray and assign to it the values of the elements separated by commas and enclosed in square brackets. If you don’t know what data is going into the array but you know how many elements you want it to have you create a new array to hold that number of elements as in 2. To do this you use the keyword new and a method of the Array object Array followed by the number of elements in parentheses. So you create a new array to hold 6 elements and assign it to the variable tmaScoreArray. All the elements of that array will be undefined. They will have nothing in them until we add some numbers to initialise the array. Suppose we now know the numbers – the scores – we can add them to the array by accessing the array elements as we saw in the last slide. For the first element we say tmaScoreArray[0] is assigned 92; for the second, tmaScoreArray[1] is assigned 87, etc. You don’t have to initialise all the elements if you don’t know the scores yet. Elements don’t have to be numbers, they can be characters or strings even other arrays!
  5. So you declare an array that is empty and assign values to its elements.
  6. For example you can assign the value in an element of an array to another variable. Here we have declared and initialised the array tmaScoreArray and declared a variable tma1. Into that variable we have assigned the value that is at index 0 in the array. You can also access an array element directly and, for example, write it out. The output is the same for both methods.
  7. In JavaScript the Array object has a length property. The length of an array is one more than the index of the last element because the index starts at zero.
  8. Whether you: declare and initialise an array with six elements explicitly, or declare an array with six empty elements, or declare a new array with six elements not yet initialised, they all have length 6. If this array was half full it would still have length 6.
  9. Having declared and initialised the array we write out the length of the array. studentArray.length gives us the length and that is concatenated to the string ‘Array length is:’. We can also use the length property to access the last element in the array. You remember we access an array element by using the array name followed by the index in square brackets. studentArray.length is 6 so studentArray.length – 1 is 5, so we are accessing the element at index 5 – the last element in the array.
  10. Structured English is used in planning an algorithm. Some of the same keywords are used that are used in the program and the layout of the algorithm is similar to the layout of the program. This structured English is sometimes called pseudo code. To go through our student array and write out a list of names the algorithm in structured English would be: for each student name in the array write out the name end for
  11. You can use the for loop to process the array elements one by one. This program fragment writes out the list of names in the array and is translated into JavaScript from the structured English on the previous slide. We have to declare a variable for the loop counter (i in this case), specify a starting value (0 because it matches the start of the array), decide on a condition (i &lt; studentArray.length) … Q In the condition why don&apos;t we say i &lt;= studentArray.length? Because the length is 6 but we want to leave the loop after the element at index 5 so we say as long is i less than 6 execute the loop. We started at element 0. Also this is useful if you don&apos;t know how many elements there are in the array. ... and finally state a rule for incrementing the loop counter – increment it by 1. i is often used as a loop counter in programming, and if you need a second one for some reason j is used. Also it&apos;s short and doesn&apos;t take so much room up on the slide! The unit has used month in its rainfall examples because month is meaningful in that context. Q What more meaningful variable name for our loop counter could we have here?
  12. We can join the output from two arrays or parallel arrays. We have the studentArray we had before and we have a another array called surnameArray, both initialised. We got through the loop again writing out an element from studentArray, then a space, then the corresponding element from sturnameArray at the same index.
  13. Output from previous slide
  14. We can combine the two arrays into a third array – fullNameArray. We have the same two arrays again and we declare a new array, fullNameArray, that is not yet initialised. Then we loop though a for loop concatenating the names from studentArray to the names from surnameArray, each in turn, and assigning them to elements of fullNameArray. Then we write out the new values in fullNameArray. This has the same output as the previous program.
  15. This is the example on page 19 of Unit 8. The structured English algorithm for the program is near the top of the page. It is an array of students&apos; marks where you don&apos;t know the number of students to start with or what the marks are, so you have to prompt for the number of students first. You have declared a variable, numberOfStudents, to hold the number of students so you read it into that. At the same time as you are reading that in you parseFloat it because you need it to be a number. You&apos;ve already declared a variable markArray to hold the array but now you know how many students you&apos;re going to have you can initialise markArray by creating a new array of size numberOfStudents and assigning it to markArray. Once your array has been created you can then loop through it prompting for the mark for each index in turn.
  16. Previously we wrote out a list of student names which didn&apos;t mean anyhting on it&apos;s own so now we are going write out a bit of explanation and the position in the array as well, using the index. The bits we&apos;ve added are in shocking pink! In the write statement in the for loop we want to write out the position in the array (not the index) so we put (i + 1) and it must be in parentheses or else the interpreter will regard it as a concatenation. Also whatever is in the inner parentheses will be evalutaed before the outer parentheses.
  17. Output from previous slide.
  18. In this program we want to find the maximum number of hours of TV watched per day, over a week. This is our algorithm in natural English: First we initialise array of TV hours watched for 7 days (that may already have been done somewhere else in the program) Then we initialise maximum TV hours watched to hours in day 1 (index 0). Then for each day of the week except the first we compare the hours of TV watched with the current maximum hours and if it is bigger replace current maximum with that days hours and end the for loop. Then we write out the final maximum number of hours
  19. This is the program to find the maximum number of hours of TV watched per day, over a week. We have a variable to hold an array containing number of hours of TV watched every day for a week starting on Sunday. We also have a variable to hold the maximum number of hours of TV watched which we initialise to first element in array – the element at index 0. Then we are going to work our way through the array starting at the second element (index 1) and see if each in turn is bigger than the maximum, which is held in maxTvHours. If it is bigger then that number is assigned to maxTvHours. When the loop is exited maxTvHours will hold the maximum number of hours of TV watched for that week. We can then write it out. Q Why do we start the loop at index 1? Because we have already looked at the first element and we are going to compare it with the second. This is OK but it doesn&apos;t tell us which day of the week has the maximum number of hours of TV watched. Activity 2.6 and Exercise 2.3 show you how to do it using two for loops.
  20. To improve the output, and write out what day most hours of TV were watched, we need to keep track of the index of the element with the biggest number of hours. So we will need a variable to to store that index. Here I&apos;ve declared maxIndex to store the index of the element with the biggest number of hours. We initially set it to zero and it will be updated each time a higher number of hours is found as it goes through the loop. This time we write out, after exiting the loop, the string, &apos;Maximun hours of TV watched was: &apos; concatenated to tvHoursArray[maxIndex], i.e. the element of the array at the index where the maximum value is, concatenated to the string &apos; on day &apos; concatenated to (maxIndex + 1), the position in the array of the element with the biggest value. Don&apos;t forget the parentheses round (maxIndex + 1) and don&apos;t forget the spaces. Q Has anybody any idea how we could improve that further? We could have seven if statements saying if maxIndex = 0 write out Sunday, if maxIndex = 1 write out Monday … etc. Later you&apos;ll learn a programming construct where you execute a different bit of code depending on a number of different choices, it&apos;s called a switch statement.
  21. [Omit if time short.] Another way to do it is to go through a loop updateing maxTvHours and maxIndex in one loop. First we need a variable to hold the index of the day that has the maximum number of hours. I&apos;ve called that maxIndex and initialised it to 0. Then in the if statement if we find a that the hours of TV watched for a particular day is greater than maxTvHours we assign the index of that day to maxIndex. At the end we write out what we wrote out before concatenated to &apos; on day &apos; concatenated to (maxIndex + 1) because the index starts at 0 and we want the position in the array. Don&apos;t forget the parentheses round (maxIndex + 1) and don&apos;t forget the spaces.
  22. We&apos;ve briefly mentioned Objects and Math is another object (don&apos;t forget objects start with capital letters). One method of the Math object is round(). It rounds a decimal, or real, number up or down to the nearest whole number. So 12.2-something will be rounded down to 12 and 12.7-something will be rounded up to 13.
  23. A complicated program can be broken down into smaller subtasks and in JavaScript these subtasks are called functions. The course style is to put the code for the functions before the main program. The keyword function comes first followed by the function name, doSomething, and the name is followed by a pair of parentheses. Sometimes we want to pass some information to the function that the function is going to use and this goes in the parentheses. It is called an argument. You must have the parentheses whether you are passing any information to the function or not. The first line of the function is called the header and statements are in the body. The beauty of a function is that you can use it as many times as you want within a program, or in different programs, and you only have to write the code once. Also, if at some future date you decide to change the function slightly, you only have to change the one bit of code and not go searching through hundreds or thousands of lines of code to find bits you want to change.
  24. In the first example we have a function that just does something – write out Hello – we don&apos;t have to pass it an argument. To use the function we have to call or invoke it and then it writes out Hello. The second one has an argument. In the function definition it is called name and name stands in for the actual argument we are going to pass it. So we invoke the function as before but we pass it the string &apos;Rita&apos; by putting it in the parentheses. The string &apos;Rita&apos; replaces name in the function body. It then writes out Hello! Rita. You don&apos;t have to pass the actual string (a string literal) or number or whatever, you can declare a variable and perhaps prompt the user for a name then assign it to the variable, then pass the variable to the function. The argument, name, is only meaningful inside the function. It is not available outside the function.
  25. A simple program might look something like this. We have the usual HTML tags. The function is declared first inside the &lt;script&gt; tag at line 7. We declare a variable myName at line 12, then we prompt for the name and assign it to the variable myName at line 14. We then call or invoke the function, sayHelloSomebody(name), passing myName as an argument in the parentheses, at line 16. myName then replaces name inside the function. The main program may be in the main body between the body tags. It doesn&apos;t have to be in the head. Don&apos;t forget a suitable title and don&apos;t forget some comments. Q What does the second argument do in the window.prompt statement on line 14 - &apos;Put your name here&apos;? Puts that text in the prompt dialogue box by default. Q What is line 7 called? The function header.
  26. The functions we&apos;ve just looked at just did something useless – sorry!– trivial, but you can have functions that return a value to you that you can do something with. Functions can also have more than one argument. We use the keyword return to tell the function to return whatever comes after it, then what is returned is available to the program that called the function. In example 1 we have declared a variable called sum. We then call or evoke the function total() with the arguments 2 and 3, separated by commas. The value that is returned is assigned to the variable sum. In example 2 we have included the function call directly in the write statement. The function call will be evaluated first and return the total then document.write will write it out.
  27. The arguments you use when you call a function, not surprisingly, are called the actual arguments . The arguments in the function definition are called the formal arguments . When you call a function the actual arguments replace the formal arguments.
  28. In olden days you had to use a command line interface and you had to remember exactly all the commands and type them into DOS or Unix, and it wasn&apos;t very pretty. You didn&apos;t even get a screen at first, the output went to a printer. Now we have graphical user interfaces, or GUIs, where we can just hold the mouse over an item and get a drop-down menu or click on a button to do something. The buttons, menus and text boxes etc are generally called widgets but in JavaScript they&apos;re known as elements in the HTML pages.
  29. To use widgets you have to create a form to put them on and the form has to have a name. The form is in the Document object (the page on the screen) and the Document object is in the Window object. If the top button is called helloButton, what it says on it is its value and the form we&apos;ll called form1 we would refer to the vlue on the helloButton as: document.form1.helloButton.value
  30. First create the form in the body of the HTML document using opening and closing HTML form tags. Look at the text box first. You create it with the INPUT tag and then set its attributes. We give it the type &amp;quot;text&amp;quot;, the name &amp;quot;helloBox&amp;quot; and the value &apos;&apos; an empty string. We want to click the button and have some text appear in the text box but before we click the button we want nothing in the text box so we set its value attribute to an empty string. Now look at the button. Its type attribute is &amp;quot;button&amp;quot;, its value (that&apos;s what it says on the button) is &amp;quot;Try me&amp;quot; and its ONCLICK event is to write in the text box Hello! What&apos;s in its value attribute appears in the text box, helloBox. To start with there&apos;s nothing in helloBox so to tell the helloBox what we want it to display we say (reading from right to left) the value of helloBox in form1 in the document object is Hello! – when we click it. This bit of code that says what&apos;s to happen when the button is clicked is called the event handler. You can use functions as event handlers. You can define a function and make afunction call as the ONCLICK event.
  31. Another ONCLICK event could be to produce an Alert dialog box. alert() is a method of the Window object and what you put in the argument is what appears in the alert box.
  32. We also have a confirm dialog box. When you click the button this confirm box appears. If you click OK it returns the Boolean value true, if you click Cancel it returns false. So in a program where you were using a confirm box you could write an if/else statement depending on whether the confirm box returned true or false. To demonstrate this …
  33. Here I&apos;ve asked it to write the value returned by the confirm box after OK or Cancel has been clicked. I clicked OK and it wrote out true – the value that was returned. If OK is clicked then (window.confirm(&apos;Do you still love me?&apos;)) evaluates to true so document.write writes out true. That value could be used elswhere in the program.
  34. Figure 5.1 on page 68 of Unit gives us a reminder of what we&apos;ve done so far on strings and introduces another method of String objects - indexOf(). myString.length is 12 mystring.charAt(5) is space myString.indexOf(&apos;d&apos;) is 10
  35. In the function we need to test whether a character is &apos;a&apos;, &apos;b&apos;, or &apos;c&apos;? Q How do we do that? We could say: if (aChar == &apos;a&apos;) || (aChar == &apos;b&apos;) || (aChar == &apos;c&apos;) { return true }; But the way shown on the slide is more elegant. However this way is not wrong and it&apos;s more explicit and less mysterious and if you want to do it that way while you&apos;re learning, because you understand it better, that&apos;s OK. We&apos;ve declared a variable – inputChar - and prompted for input that we&apos;ve assigned to it. If inputChar is lower case a, b or c we write it out, if not we tell the user the character wasn&apos;t a, b or c. Q So what condition do we want in the if statement, bearing in mind we&apos;ve just created a function that returns true or false? if(isabORc(inputChar)) It is a call to the function isabORc(inputChar) and if it is the condition in the if statement it&apos;s like saying &apos;if true …. else …. &apos;