1 of 11

Arrays (Java/Turing)

CPT Girls

2 of 11

What are we covering?

  • When to use an array
  • What is an array
  • Syntax
  • Helpful commands for arrays
  • Extending - Parallel arrays

3 of 11

When to Use Arrays

  • Let’s say you needed to create a program that would allow the user to input 15 names. Once all input has been received, it outputs all 15 names.
  • To do this, you could use 15 variables…
  • Or you could use an array!

4 of 11

What is an array

  • A list of values being stored
  • An index (number) is assigned to each value
  • Could be any data type
  • In Java and Turing, you may only store one type of data in a given array
  • Regular arrays hold a fixed number of objects (you must give the size of the array when creating it)

5 of 11

What is an array

  • The pieces of data put in an array are called elements
  • Each element is assigned an index
    • Indices start at 0 in Java
    • Indices start at any integer you’d like (even negative!) in Turing
    • In Turing you can also have any keyboard character as indices (so instead of an index of 0 to 4 you could have ‘A’ to ‘F’)
    • Note though that the starting index must be smaller than the stoping index

6 of 11

What is an array

Example of Java/Turing number indexes

Example of Turing character indexes

Indices

0

1

2

3

4

Elements

“CPT!”

“is!”

“the!”

“coolest!”

“club!”

Indices

A

B

C

D

E

Elements

“CPT!”

“is!”

“the!”

“coolest!”

“club!”

7 of 11

Syntax

Turing

Java

Initialization

var [arrayName]: array [start index] .. [stop index] of [data type]

int [] myArray = new int [5]

Assignment

my_array(0) := 17

myArray[0] = 17

Comparison

if my_array(0) = 17 then

if (myArray[0] == 17)

Index number

Index number

8 of 11

Helpful commands for arrays (Turing)

  • upper (arrayname) → returns the upper bound/stopping index of the array (for char arrays it will return the ASCII value of the char)
  • lower (arrayname) → returns the lower bound/starting index of the array (for char arrays it will return the ASCII value of the char)

9 of 11

Helpful commands for arrays (Java)

  • Arrays.sort (arrayname) → will sort array in ascending order
  • Arrays.toString (arrayname)→ returns a String representation of specified array
  • arrayname.length→returns the size of an array

10 of 11

Extending - Parallel Arrays

  • When you have lists of data which are related
  • Ex: A list of names and a list of their heights
  • You need 2 arrays, for the names and heights
  • You store the data so that the height belonging to a name have the same indices

Indices

0

1

2

3

names

Jaclyn

Yuan

Hannah

Tina

heights

149

169

164

172

11 of 11

Example problems