Professional Documents
Culture Documents
Arrays
• Is a collection of variables of the same type, referred to by a common
name.
• Arrays are data structures consisting of related data items of the same
type. Each item of an array is called an element. The position number
of the element is called the element’s index or subscript. The first
element in every array has index zero.
Consider the example:
int num1 = 1;
int num2 = 5;
int num3 = 6;
for (x=0;x<5;x=x+1)
{
sample[x] = x;
}
for (x=0;x<5;x=x+1)
{
System.out.println ("Array Number [" + x + "]: " + sample[x]);
}
}
}
Output:
class ArrayEx {
public static void main (String args[]) {
int num [] = new int[5];
int min=0, max=0, x;
num[0] = 10;
num[1] = 0;
num[2] = 12;
num[3] = 14;
num[4] = 69;
min = max = num[0];
for (x=1; x<5; x++)
{
if (num[x] < min)
min = num[x];
if (num[x] > max)
max = num[x];
}
System.out.println ("Min and Max: " + min + " " + max);
}
}
Use Array Initializers
class ArrayEx {
public static void main (String args[]) {
int num [] = {12,44,145,1,124};
int min=0, max=0, x;
min = max = num[0];
for (x=1; x<5; x++)
{
if (num[x] < min)
min = num[x];
if (num[x] > max)
max = num[x];
}
System.out.println ("Min and Max: " + min + " " + max);
}
}
Demonstrate an Array overrun.
class ArrayEx {
public static void main (String args[]) {
int num [] = new int[5];
int x;
for (x=0; x<100; x=x+1)
{
num[x]=1;
System.out.println ("Num: " + x);
}
}
}
Sorting an Array
• Because a one-dimensional array organizes data into an indexable
linear list.
• The best known, simplest, and easiest to understand is called the
Bubble Sort.
Bubble Sort
• Gets its name from the way it performs the sorting operation. It uses
the repeated comparison and, if necessary, exchange of adjacent
elements in the array.
• In this process, small values move forward one end and large ones
toward the other end.
Example:
for (x=1; x<size; x++)
for (y=size-1; y >=x; y--) {
if (num[y-1] > num[y]) {//if out of order
//Exchange Elements
t = num[y-1];
num[y-1] = num[b];
num[y] = t;
}
}
class ArrayEx {
public static void main (String args[]) {
int num [] = {212,41,516,125,312};
int x, y, z, a;
int size;
• This two-dimensional array will have two rows and four columns.
2 4 7 15
3 1 8 10
public class twodimenarray1 {
int t, i;
int table [] [] = new int [3] [4];
}
}
Using the length member
• Because arrays are implemented as objects, each array has associated
with it a length instance variable that contains the number of
elements that the array can hold.
public class twodimenarray1 {
}
}
End…