Arrays Structured data Arrays What is an array?

Similar documents
COSC 122 Computer Fluency. Iteration and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Iteration and Arrays Dr. Abdallah Mohamed

CSC Web Programming. Introduction to JavaScript

Working with JavaScript

JavaScript Basics. The Big Picture

HTML5 and CSS3 More JavaScript Page 1

3rd Grade Math Pacing Guide Saxon Math First Nine Weeks

Javascript Lesson 3: Controlled Structures ANDREY KUTASH

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

COMS 469: Interactive Media II

Such JavaScript Very Wow

Calculations with Sig Figs

3 The Building Blocks: Data Types, Literals, and Variables

Grade 4 Math Proficiency Scales-T1

COMS 469: Interactive Media II

Exercise: Using Numbers

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Topic 2: Introduction to Programming

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

CMPT 100 : INTRODUCTION TO

DEPARTMENT OF MATHS, MJ COLLEGE

Lab 1. Purpose. Assignment. Action Items/Programming Requirements

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Computer Science 236 Fall Nov. 11, 2010

Variables and Typing

Variables, Types, Operations on Numbers

1/11/2010 Topic 2: Introduction to Programming 1 1

JavaScript CS 4640 Programming Languages for Web Applications

Square roots: We say that the square root of 16 is 4. We write this as 16 4.

NUMBERS AND NUMBER RELATIONSHIPS

Main Memory Organization

Concept Fourth Grade: Second Nine Weeks Readiness Standards Time Key Content Key Vocabulary

CSI33 Data Structures

Unit 1: Numeration I Can Statements

CHAD Language Reference Manual

CHAPTER 4: DECIMALS. Image from Microsoft Office Clip Art CHAPTER 4 CONTENTS

Concept Fourth Grade: Second Nine Weeks *Revised 5/21/15 Readiness Standards Time Key Content Key Vocabulary

Introduction to Computer Science and Object-Oriented Programming

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

C++ Programming: From Problem Analysis to Program Design, Third Edition

Converting between Percents, Decimals, and Fractions

Full file at

Variables and Data Representation

Chapter 17. Fundamental Concepts Expressed in JavaScript

Gateway Regional School District VERTICAL ARTICULATION OF MATHEMATICS STANDARDS Grades K-4

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Tutorial 10: Programming with JavaScript

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Cambridge International General Certificate of Secondary Education 0478 Computer Science June 2015 Principal Examiner Report for Teachers

Properties. Comparing and Ordering Rational Numbers Using a Number Line

C Functions. 5.2 Program Modules in C

CSCE 120: Learning To Code

MATHS. years 4,5,6. malmesbury c of e primary school NAME CLASS

Numerical Methods in Scientific Computation

Math STAAR- Grade

Rev Name Date. . Round-off error is the answer to the question How wrong is the rounded answer?

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

YOLOP Language Reference Manual

Programming Basics. INFO/CSE 100, Spring 2006 Fluency in Information Technology.

Bridge. Calculated Fields Guide. Version

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

6.001 Notes: Section 4.1

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

PLD Semester Exam Study Guide Dec. 2018

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

These are square roots, cube roots, etc. Intermediate algebra Class notes Radicals and Radical Functions (section 10.1)

Math 155. Measures of Central Tendency Section 3.1

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

An overview about DroidBasic For Android

Introduction to Programming in Turing. Input, Output, and Variables

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Lab 1 Concert Ticket Calculator

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

TIMSS 2011 Fourth Grade Mathematics Item Descriptions developed during the TIMSS 2011 Benchmarking

Number Sense Third Grade Fourth Grade Fifth Grade MA.4.NS.1.a.1: Read, demonstrate, and write whole numbers up to 500.

ITEC136 - Lab 2 Population

Programming for Engineers Iteration

FUNCTIONS. The Anatomy of a Function Definition. In its most basic form, a function definition looks like this: function square(x) { return x * x; }

Everyday Math and the Indiana Academic Standards for Grade 4 Mathematics

Intermediate Algebra. Gregg Waterman Oregon Institute of Technology

JavaScript CS 4640 Programming Languages for Web Applications

Sketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Anatomy of a Function. Pick a Name. Parameters. Definition. Chapter 20: Thinking Big: Programming Functions

Topic C. Communicating the Precision of Measured Numbers

6.001 Notes: Section 6.1

egrapher Language Reference Manual

Control Structures II. Repetition (Loops)

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Unit 7 Number System and Bases. 7.1 Number System. 7.2 Binary Numbers. 7.3 Adding and Subtracting Binary Numbers. 7.4 Multiplying Binary Numbers

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

CSC 101: Lab Manual#9 Machine Language and the CPU (largely based on the work of Prof. William Turkett) Lab due date: 5:00pm, day after lab session

C++ PROGRAMMING SKILLS Part 4: Arrays

Table of Contents. Oceanwide Bridge. User Guide - Calculated Fields. Version Version Bridge User Guide User Guide - Calculated Fields

Transcription:

The contents of this Supporting Material document have been prepared from the Eight units of study texts for the course M150: Date, Computing and Information, produced by The Open University, UK. Copyright The Open University, UK. Introduction In Unit 7 you learned to store, retrieve, and manipulate simple data items such as numbers, strings and Boolean values, and to carry out simple operations on this data, using the basic control structures of sequence, repetition and selection. In this unit, we move from the manipulation of single-valued data to the use of an array as a simple example of a data structure. Such data structures allow us to handle collections of related data, e.g. rainfall figures for each month of a given year, as a single named entity. This unit starts to look at the ways in which we can write separate pieces of code, known as functions, to handle each of the subtasks required in a program. You will see how these functions can then be combined or reused, as and when required, to create an overall program to carry out a particular task. 1

Structured data There are many situations where we want to deal with a collection of data values that are related to each other in some way. For examples: The total rainfall (recorded in millimeters) in our local area for each month of a given year. The titles of all the tracks on our favorite CD. In processing such collections of data values, we will often want to treat each value in a collection in a similar way. What is an array? Collections of data values come in many different patterns. A pattern is a collection consisting of a list of data values that are all of the same type, e.g. all numeric values or all string values, and where the important relationship between the values is their relative position in the list. In most programming languages: The name given to such a data structure is an array. And we talk about each data value as an element of the array. The position of an element in the array is then given by an index. 2

Figure 2.1 shows an array of five elements, each of which is a number, with the associated index values, running from 0 to 4. As with strings, the index values of arrays in JavaScript are numbered from 0 rather than from 1. This feature is known zero-based indexing. An array variable needs a name to identify it, e.g. myarray in Figure 2.1. The way that JavaScript (and most other programming languages) accesses the individual elements of an array is by using square brackets, so that myarray[3] is the fourth element in the array and has the value 7. Declaration and initialization of arrays In JavaScript, array data structures are represented and manipulated using the built-in Array object. In a JavaScript array, when you know the exact number of elements and their values, the simplest way to declare the array is as follows. var rainarray = [111,115,200,95,23,59,68,33,39,144,66,37] We have given the array the variable name rainarray and have included the list of monthly rainfall data values in millimetres (mm) as successive elements, in a comma-separated list enclosed by square brackets. In fact, by providing a list of values, we have initialized as well as declared our array. The JavaScript interpreter recognizes this as an array declaration because the data is enclosed in square brackets. The state of the array after this declaration is shown. 3

If you know the number of elements in an array, but expect the actual values to be provided later, during the execution of the program, then you can simply reserve memory for the array, as follows. var rainarray = new Array(12) The JavaScript reserved word new is used to create a new Array object and this statement will set up the array and provide enough memory for the 12 elements that are to be stored in it. Since we have not yet provided any values for the array elements, they have the special default value of undefined, and it would be wrong to try to retrieve or manipulate what is stored in these memory locations before values have been assigned to them. The figure shown shows the array where question marks denote the value undefined. Accessing individual array Having set up an array you need to be able to initialize or modify the values of its elements and to read in and write out these values. You can do this using the square bracket notation for arrays. For example, if you want to set received a mark of 95 for the second TMA of this course then you could record that in mym150markarray, using the following assignment statement. mym150markarray [1] = 95 To retrieve and use the current values of elements already present in our arrays you can use statements such as: februaryrain = rainarray [1] previoustma01mark = previousmarkarray [0] To write the current value of an array element directly to the document in the browser window you can write statements like: document.write('my mark for TMA02 was ' + mym150markarray [1]) 4

Array length As with the String objects discussed in Unit 7, JavaScript Array objects have a length property, which indicates the number of elements in the array. To find the length of an array named myarray, we use myarray.length. It is important to remember that the length of an array is one greater than the index value of its last element so that, for example: weekdayarray.length has the value 7, but the last day of the week is weekdayarray [6]. More generally, the last element in an array called somearray can be accessed assomearray [somearray.length 1]. Processing the elements of an array using a for loop In Unit 7 you learned about the for loop control structure for handling repeated actions when you know how many data items need to be processed. We often want to apply essentially the same operation to every element of an array, such as entering data values, transforming data values or outputting data values. By taking advantage of the length property, a for loop can be used to iterate through the elements of an array. Examples on some common activities carried out on array data structures are: Outputting all the elements of an array. Carrying out transformations on each element. Summing the values in a numeric array. Entering data values into an array. Finding the maximum or the minimum value in an array. 5

Planning the steps in a programming task An algorithm is a clearly specified set of instructions to be followed in order to carry out a task or obtain a solution to a problem. This generally consists of a number of activities to be undertaken, with appropriate sequence, selection and repetition. It is useful to have a way of representing the algorithm for a programming task that is independent of the language in which the program will be written. One approach is to use flowcharts, which are diagrams similar to those used in Units 6 and 7 to illustrate looping and conditional structures. Another approach is to write instructions in a restricted subset of English, together with keywords similar to those found in programming languages. The layout of the text also gives some visual indication of its structure. Instructions written in this way are known as structured English. Outputting all the elements of an array A common requirement is to produce a list of the values of the elements in an array. We can use structured English to express the steps in writing out the rainfall figures in the rainarray as follows. for each month of the year write out the rainfall figure for that month end for Note the use of the word for to indicate the need for repetition, the indentation of the write statement, and the explicit closure of the loop by the words end for. 6

In order to translate this into a JavaScript for loop structure we need to: Declare a variable, such as month, as a loop counter; Specify a starting value for month, in this case 0 to start at the first element of the array; Formulate the condition for iterating round the loop. Given that counting starts at 0, this will be month < rainarray.length. Finally, state the rule for incrementing the loop counter. Since we want every value to be output, month = month + 1. Putting these together gives the following JavaScript code. for (var month = 0; month < rainarray.length; month = month + 1) { document.write(rainarray [month] + '<BR>') } Carrying out transformations on each element Suppose the rainfall data is required in inches as well as in millimeters. The constant to convert millimeters to inches is 0.03937, so each data value needs to be multiplied by 0.03937. We can use a for loop to carry out this activity, converting each value in turn. An additional Array variable, say inchrainarray, is needed to store the converted values. In structured English we could write the task as follows. for each month of the year set rainfall in inches to rainfall in mm * 0.03937 and store it in the equivalent position in inchrainarray end for 7

This can be translated directly into JavaScript, as follows. for (var month = 0; month < rainarray.length; month = month + 1) { inchrainarray [month] = rainarray [month] * 0.03937 } The figure below shows what happens. Once a collection of data values have been entered into an array, there are many ways that they could be processed, such as the following. Carrying out a simple, identical transformation on each element (e.g. as in the conversion of mm to inches). Transformation is the process of manipulating one piece of data so as to produce another, e.g. performing a calculation on a number or changing the characters in a string, say from upper to lower case. Finding the total value of all the numeric elements in an array or identifying the largest or smallest element. Finding out whether a particular value is currently stored as an element of the array and, if so, in what position(s) in the array it is stored. Sorting the elements in an array according to some rule, e.g. in increasing order of size if the elements are numeric or in alphabetical order if the elements are text strings. 8

Summing the values in a numeric array Given the array of rainfall values for each month of the year, we may be interested in knowing the annual rainfall for the year. This involves adding up all the values that are stored in the array and keeping track of the running total. In this case we need to declare and use a new variable to store the total, which we will call annualrainfall, which needs to be initialized (to 0) before the process of adding can be started. The value of each element of the array then needs to be added to the total, annualrainfall. As all the elements of the array need to be processed and the array s size is known, a for loop can handle the repetition involved. Finally, the value of annualrainfall can be displayed. A structured English statement of this is given below. initialize the rainfall total to zero for each month of the year add the rainfall for that month to the current rainfall total end for write out the final rainfall total This can be translated directly into JavaScript, as follows. annualrainfall = 0; for (var month = 0; month < rainarray.length; month = month + 1) { annualrainfall = annualrainfall + rainarray [month] }; document.write ('Annual rainfall = ' + annualrainfall + ' mm') 9

Entering data values into an array In structured English: In JavaScript: Finding the maximum value in an array In structured English: In JavaScript: 10

Managing the precision of numeric output JavaScript handles numbers with decimal points by displaying it with at least five figures. JavaScript provides us with a way of rounding decimal numbers to the nearest whole number through use of its Math object, which has an associated method called round(). For example, Math.round(2.4) evaluates to 2 Math.round(2.7) evaluates to 3 Unit Summary In this unit, you learned about: The array as a simple example of a data structure. 11