In an earlier tutorial, we looked at how to store a single value to a variable, similarly an array is a named place to store a SET of values allowing you to group common types.
Sometimes, it becomes necessary to order variables in a list to spot trends:
This is the ideal application for an array. All the variables and values are of the same type, integers, string, or what ever. Moreover there order and place in the list is important. Since an array allows you to store a “list” of values as a single “variable,” there must be a means of referencing each item. This reference is called an index. So therefore:Temperature on Sept 1 = 90
Temperature on Sept 2 = 87
Temperature on Sept 3 = 84
If
ThenCode:Temp[1] = 90 Temp[2] = 87 Temp[3] = 84
At first, a concept that is difficult to grasp is that the index starts at 0. There for, an array with 5 elements contains the index values {0, 1, 2, 3, 4} but how do we make an array?Code:int x = 2; Temp[ x ] = 87;
A working example might look like this:Code:int z[ ] = new int[5];
Therefore z[4] = 4! Arrays do not have to be numbers, for example:Code:int x; int z[] = new int[10]; for (x = 0; x < 10; x++) { z[x] = x; }
You can accomplish the same thing in less lines of code by using the following:Code:int x; String myArray[ ] = new String[5]; myArray[0] = "hello"; myArray[1] = "this"; myArray[2] = "is"; myArray[3] = "an"; myArray[4] = "array"; for (x=0; x <= 4; x=x+1 ) { System.out.println( myArray[x] ); }
If a single list of values isnt powerfull enough, we also have the ablilty to use miltidimensional arrays. This is sometimes refrered to as a matrix. Each index has its own set of indicies that are pared with it, for example:Code:int x; String myArray[] = {"hello", "this", "is", "an", "array"}; for (x=0; x<=4; x++){ System.out.println( myArray[x] ); }
Code:int matrix[][] = {{1,2,3,4}, {4,5,6,7}, {7,8,9,10}}; for (int i=0; i<=2; i++){ for (int j=0; j<=3; j++){ System.out.println( matrix[i][j] ); } }


LinkBack URL
About LinkBacks







Reply With Quote








Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum