Pages

4.05.2012

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!

2 comments:

  1. Can you modify the length of an array while in a program? Say, I define int a[3], but later I want to concatenate a to itself, resulting in an array with length of 6?

    ReplyDelete
  2. I do not believe this is possible. In order for this to happen, we'd need the ability to dynamically allocate array memory (i.e. create an array of a length to be specified during the program); but, as far as I can tell from my own tests and some online research, this capability does not exist in ROBOTC. (An example: http://www.robotc.net/forums/viewtopic.php?f=1&t=4956)

    ReplyDelete

Please keep comments clean! Thanks.

Note: due to comment moderation, it may take a while for a comment to display.