6. Arrays

You must first complete 5. Stall detection before viewing this Lesson

4.1. Why Use Arrays?

Simplify programs by storing multiple related values in a single variable
Can be used with loops to make compact and useful programs
Are useful for making a custom calibration program (see NXT Light Sensor in EV3 on our contributed lessons tab)

4.2. What is an array?

An array is a variable that holds multiple values
There are two types of arrays:
Numeric Array (Holds a set of numbers … 1,2,3,10,55)
Logic Array (Holds a set of logic … True, True, False)
They can be used as either Inputs or Outputs so you can either….
Write – put a value(s) into the array
Read – get the value(s) from the array out

4.3. Array Blocks: Quick Guide

Array Indexes
Each value in an array is assigned an index
The first value would be at index 0
Logic arrays would store True/False instead of numbers
To add a value to an array click the plus +
This adds an entry at the next index value (i.e. index 3

4.4. Block: Array Operations
This block is used to read or write to Logic or Numeric arrays

Different modes:
• Append: Add a new entry after the last array index
• Read at index: Reads the value at a certain index
• Write at Index: Write a new value to a certain array index
• Length: How many entries are in the array
Both write and append output an array  you will need to write this array back to the variable if you wish to update the stored array

How do you use Arrays (Reading)?

How do you use Arrays (Writing)?

4.5. Block Setting: Loop Count
The loop count outputs the amount of times the blocks inside the loop have played.
This is useful to create a program that runs different code every time it goes in the loop
It is also useful for computing on each item of an array

Note: Append vs. Write

Challenge 1
Make a program that displays all the entries of an array. Display each index on a different line. You can use only one display block.
Tips: You will need to use loops, loop count, array block, array operations

Challenge 2
Make a program that adds up all the entries of an array. Display the sum.
Tips: You will need to use loops, loop count, array block, array operations

More fun things to try:
Make a program to compute the average value in an array
Make a program that always saves the last 4 light sensor readings in an array
Create an array that stores calibration values for each sensor port

Back to: Module 4. Robotics Coding and Driving