Arrays in ROBOTC

I’ve seen multiple people ask how arrays work in ROBOTC, so I thought I’d write a post about arrays.  Note: I’m going to be describing several routines here that require a knowledge of loops.  Loops are, in general, something that you should have a pretty good handle on in order to take advantages of arrays.

First: What is an array?  Basically, an array is a list of variables all declared at once.  Think of it like a table:

This table represents the integer array aa has length 6, and is declared with the statement:
int a[6];
You access individual cells by their index.  Indices start at 0 and continue to length – 1.

So, a[3] is equal to 256.

How is this useful?  Well, let’s say we wanted to store 3 light sensor values, each taken 1 second apart.  We could define 3 variables, as in this example:

int value1 = SensorValue[light];
wait1Msec(1000);
int value2 = SensorValue[light];
wait1Msec(1000);
int value3 = SensorValue[light];

This is all well and good, until you decide that 3 value isn’t enough.  Let’s say you now want to store 100 light sensor values.  Well, you don’t want to have to define 100 variables, and then type out each assignment!  So, you can use an array:

int values[100];
for(int i = 0; i < 100; i++){
  values[i] = SensorValue[light];
  wait1Msec(1000);
}

So, what’s going on here?  Well, first, we declare an array with a capacity of 100 integers.  Then, we iterate through each cell of the array and set its value to the current light sensor reading.  The program then waits one second before looping.

So far, I’ve only covered 1 dimensional arrays.  ROBOTC supports 2 dimensional arrays as well.  Just like before, a table is helpful to visualize this:

The first number in square brackets determines the row, and the second number determines the column.  So, in the above array, a[1][2] is equal to 48, and a[2][1] is equal to 58.

To declare a 2d array of the same size as the above array, use:
int a[3][6];

I hope this helps explain arrays in ROBOTC.  If you have any questions, please leave a comment!

Posted in NXT, Robot Programming, ROBOTC, Tutorial, VEX

Twitter