things_to_buy
---
0) Apples
1) Bananas
2) Milk
3) Cheese
What's the length of this list? Well, it's four. There are four things on the list. What's the first (0th) thing on the list? It's Apples.
Here's a list of numbers:
nums
---
0) 37
1) 26
2) 62820
You might declare this list like this:
int[] nums = { 37, 26, 62820 };
But you might not know what numbers are in the list when you declare it - you might only know the length.
int more_nums = new int[100];
So now if you want to assign each number in that list to the index of that number's position, you would use a loop:
for( int i = 0; i < more_nums.length; i++){
more_nums[i] = i;
}
You can see that this loop starts with the first (0th) number in the list, and assigns it the value of 0. Then it goes to the second number (at index 1), and assigns it the value 1. And so on, up to the 99th index. Notice that more_nums[100] is not on the list!
int[] nums = { 37, 26, 62820, 223, 12, 66 };
println (nums.length);
int b = 3; // b is the index (counting starts at 0)
println (nums[b]);
println("=======================");
println("Entire array: ");
printArray (nums);
println("=======================");
for ( int i = 0; i < nums.length; i++) { // doing something with the array
print ( nums[i] * 3 + ",");
} // end of for-loop
Or with an array of String
String[] nums = { "Milk", "Butter", "Honey", "Chocolate" };
println (nums.length);
int b = 3; // b is the index (counting starts at 0)
println (nums[b]);
println("=======================");
println("Entire array: ");
printArray (nums);
println("=======================");
for ( int i = 0; i < nums.length; i++) { // doing something with the array
print ( nums[i] + ",");
} // end of for-loop
Answers
Think of an array like a shopping list.
What's the length of this list? Well, it's four. There are four things on the list. What's the first (0th) thing on the list? It's Apples.
Here's a list of numbers:
You might declare this list like this:
But you might not know what numbers are in the list when you declare it - you might only know the length.
So now if you want to assign each number in that list to the index of that number's position, you would use a loop:
You can see that this loop starts with the first (0th) number in the list, and assigns it the value of 0. Then it goes to the second number (at index 1), and assigns it the value 1. And so on, up to the 99th index. Notice that more_nums[100] is not on the list!
in this expression:
a[b]
To store the index number of an array just say
int b=3;
Then use
b
as the index for the array:println(a[b]);
a.length
is the length of the array.When you think of the array as an shopping list,
a
would be the list andb
the line number anda[b]
the content of that line.See tutorial:
https://www.processing.org/tutorials/arrays/
Full working sketch:
Or with an array of String