CS4ALL Computer Science For All Of Us
  • Home
  • Community
  • Workshop
    • Workshop Info
    • Schedule
    • Location
    • Sponsors
  • Resources
    • Scratch Resources
CS4ALL
  • Home
  • Community
  • Workshop
    • Workshop Info
    • Schedule
    • Location
    • Sponsors
  • Resources
    • Scratch Resources
  • Home
  • Processing
  • Beginner
  • Arrays

Arrays

July 12, 2016 Leave a Comment Written by Keith Atkinson

If we wanted to keep track of the score in a game, we stored the current score in a variable. But what if we had a game with 100 levels and we wanted to keep track of the score that the player got at each level?

Unfortunately, variables can only store ONE thing at time, which means we would have to declare and initialize 100 variables in our program. Doing all that writing is very tedious, which is why we use arrays to initialize a lot of variables at one time. An array is like a list of variables.

How Arrays Work

Every item in the array must be the same data type, which means that an array can only store all integers or all data type array name we are initializing the array with 5 elements the brackets mean that we are declaring an array booleans or all strings.

An array has a fixed size. This means that when you declare the array, you must tell Processing how many items you are going to store in the array. So if you tell Processing you want 5 items in your array you can not increase the array size to 6 or decrease the array size to 2 later in your program.

Adding or Changing Values in an Array
Now that we’ve instantiated an array, we need to learn how to add a value or change a value in an array. We can think of arrays as a bunch of boxes lined up in a row, the first box is labeled with 0, the second with 1, the third with 2, and so on, for all the boxes in the array. These numbers are called
index positions
and they are the same for every array.

We assign a value to the array by writing the array name and the index position of of the value between brackets.

int[] scores = new int[5];
scores[0] = 3;
scores[1] = 2;
scores[2] = 3;
scores[3] = 5;
scores[4] = 1;

int[] scores = new int[5]; scores[0] = 3; scores[1] = 2; scores[2] = 3; scores[3] = 5; scores[4] = 1; for (int i = 0; i < scores.length; i++) { println(“Score ” + i + “ is ” + scores[i]); }

Finding the size of an Array
To quickly find the size of the array, we can append the .length function to the array name. In the following example, Processing will print to the console: “The size of times is: 6.”

int[] times = {12, 34, 56, 14, 39, 13};
println(“The size of times is: “ + times.length);
Beginner, Processing
Images
Scratch – Basic Program

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *