Monday, April 13, 2015

String[] topic = {"Arrays", "101"};

This unit was all about arrays, which are simply "lists" of values.

Arrays can consist of integers, strings, booleans, object references, you name it.

There are two main ways to create arrays, like this:

int[] grades = new int[10];

Which would create an empty int array of length 10, or:

String[] veggies = {"Cucumber", "Corn", "Lettuce"};

Which would create a defined String array, length three, consisting of Cucumber, Corn, and Lettuce.

Arrays are indexed starting at 0, meaning that Cucumber is at index 0. You can call a value from an array like this:

return veggies[1];

Which would return "Corn", since the array starts at 0.

You can find the length of an array similarly to a String, but instead of .length(), we remove the parentheses and just use .length:

return veggies.length;

This returns 3.

Going back to that first array I made, an int array called grades of length 10,  I can pass in some values for the empty array.

grades[5] = 99;

Now the fifth index, or sixth value, is 99.

Arrays are often used in for loops, like this:

for (i = 0; i < veggies.length, i++) {  //i will be 0, 1, and 2
  return veggies[i];   //Cycles through array and returns each value
}

or, this:

for (int i : veggies) {  //Same thing as before, but simplified
  return veggies[i];
}

You can also make use of multi-dimensional arrays, which work like matrices - rows and columns. But since this is for the "1 Dimensional Array Merit Badge", I won't go into it much here.

Basically, it lets you create an array that looks like this:

[ 0, 25,  3]
[ 1,  3, 53]
[ 3, 74,  8]

Which has three rows and three columns. Rows are horizontal whereas columns are vertical. To find the index of a particular value, you would use the format (row, column). So, that 74 right there? It would be (2, 1) because it's in row 2 (which is the third row, but remember that the index starts at 0) and column 1 (which is the second column). 

Hooray!

2 comments:

  1. Tremendous post...tremendous effort. Great work!

    ReplyDelete
  2. Tremendous post...tremendous effort. Great work!

    ReplyDelete