|
|
Explanation:
|
Note:
|
|
|
Example:
public class Length
{
public static void main(String[] args)
{
double[] a = new double[5]; // Define an array of 5 elements
double[] b = new double[10]; // Define an array of 10 elements
System.out.println( a.length ); // Prints 5
System.out.println( b.length ); // Prints 10
}
}
|
How to run the program:
|
public class Print1
{
public static void main(String[] args)
{
int i;
int n = 5;
for ( i = 0; i < n; i++ )
{
System.out.println( i );
}
}
}
|
Output:
0 1 2 3 4 |
Within the body of the for-loop, the variable i takes on all indices of an array of length n !!!
|
public class Print2
{
public static void main(String[] args)
{
double[] a = { 2.3, 3.4 , 4.5, 5.6, 6.7, 7.8, 8.9 }; // 7 elements
int i;
System.out.println( "# elements in array: " + a.length );
System.out.println( );
System.out.println( "The array elements are:" );
for ( i = 0; i < a.length; i++ )
{
System.out.println( a[i] );
}
}
}
|
Output of this program:
# elements in array: 7
The array elements are:
2.3
3.4
4.5
5.6
6.7
7.8
8.9
|
How to run the program:
|
|
|
The Brute Force Search technique:
|
Warning:
|
|
(a is some array (any type) )
int i;
for ( i = 0; i < a.length; i++ )
{
// statements in the for-loop body will be
// executed ONCE for each array element a[i]
}
|
The variable i is used as array index.
(a is some array (any type) )
for ( int i = 0; i < a.length; i++ )
{
// statements in the for-loop body will be
// executed ONCE for each array element a[i]
}
|
The reason for this special allowance to avoid Murphy's law (i.e.: what can go wrong, will)
|
The index variable i can only be used inside the for-statement.
The for-statement is "self-contained".
public class Print3
{
public static void main(String[] args)
{
double[] a = { 2.3, 3.4 , 4.5, 5.6, 6.7, 7.8, 8.9 }; // 7 elements
System.out.println( "# elements in array: " + a.length );
System.out.println( );
System.out.println( "The array elements are:" );
// System.out.println( i ); // Will cause an error: i undefined
for ( int i = 0; i < a.length; i++ )
{
System.out.println( a[i] );
}
// System.out.println( i ); // Will cause an error: i undefined
}
}
|
How to run the program:
|
Note:
|
(The designers of Java keep adding to the Java language)...
for ( elementType varName : arrayRefVar )
{
// statements in the for-loop body will be
// executed ONCE for each array element "arratRefVar[i]"
// which is represented by the variable name "varName"
}
|
Example:
public class Print4
{
public static void main(String[] args)
{
double[] a = { 2.3, 3.4 , 4.5, 5.6, 6.7, 7.8, 8.9 }; // 7 elements
System.out.println( "# elements in array: " + a.length );
System.out.println( );
System.out.println( "The array elements are:" );
for ( double x : a )
{
System.out.println( x ); // print all a[i] in array a
}
}
}
|
How to run the program:
|
Output: (same as Print2.java)
# elements in array: 7
The array elements are:
2.3
3.4
4.5
5.6
6.7
7.8
8.9
|