ONE-DIMENSIONAL ARRAY
Array is used to store many pieces of data of the same type
One-dimensional array structure
|
|
1 |
2 |
--------- |
99 |
Declare a one-dimensional array
Data type [] arrayname;
or
Data type arrayname [];
Example
int [] testScore;
or
int testScore[];
Create a one-dimensional array
Allocate the memory for the array. Define the number of array
elements
arrayname [ ] = new datatype [arraysize];
arraysize: an integer value or an integer variable
Assume that you have declared the array.
Example: Create a one-dimensional array of 100 elements.
int [] testScore;
testScore = new int[100];
Declare and initialize a one-dimensional array
int [] A = {10,60.20,5,90};
or
int A [] = {10,60,20,5,90};
|
10 |
60 |
20 |
5 |
90 |
Arrayname.length è Return array size
Example
Declare and initialize a one-dimensional array
Accumulate all the array elements
Display the accumulated value
int [] A = {10, 60, 40, 30, 80};
1st Solution
sum= A [0] +A[1] + A[2] + A[3] + A[4];
2nd Solution Use a for loop
sum= 0
for( int i =0 ; i< A.length; i = i + 1 )
sum = sum + A[i];
System.out.println( sum);
Example
Input 5 array elements of type integer form the user
Strings;
in [] A= new int [5];
for( int i=0; i < A.length; i = i +1)
{s= JOptionPane.showInputDialog” Enter a Number”);
A[i]= Integer.ParseInt(s);
}
0 1 2 3 4
|
30 |
40 |
60 |
10 |
35 |
A
Find the index of the largest array element
int largestelement = A[0];
int largest index =0;
for( int i=1; i<A.length; i++)
{ if(A[i]> largestelement)
{largestelement =A[i];
largestindex = i;
}
}
Analyze the coding
largestElement = A[0]
largestindex =0
i = 1
A[1] >largestElement à
40>30
largest Element à
A[1] = 40
largest index= 1
i = 2
A[2] >largestElement à
60>40
largest Element à
A[2] = 60
largest index= 2