Java Reference
In-Depth Information
4.4 Arrays as function arguments
Functions and procedures can have arrays as arguments too. Remember that
arrays of element types TYPE are themselves of type TYPE [] , so that the syntax
for declaring a function using an array argument and calling it is:
static void MyFunction(int [ ] x)
{...}
...
int [] v=new int[10];
// Calling the function with an array argument
MyFunction(v);
For example, consider implementing a function that returns the minimum
element of an array of integers provided as a function argument:
Program 4.6 Array argument in functions: Minimum element of an array
class ArrayMinimum {
static int minArray( int [] t)
{ int m= t [ 0 ] ;
for ( int i=1;i < t . length ; ++i )
if (t[i] < m)
m= t [ i ] ;
return m;
}
public static void main( String [ ]
args )
int [] v= new i n t
[23];
for ( int i=0;i < 23; i++)
v[ i ]=( int ) (Math . random () 100) ; // int from 0 to 99
System . out . println ( "The minimum of the array is :" +minArray
(v)) ;
}
}
Since we initialize the array by filling it with random elements using the
Math.random() function, running the code several times may yield different
outputs. For example, running the compiled bytecode three times in a row
yields the following results:
The minimum of the array is :4
The minimum of the array is :2
The minimum of the array is :1
 
Search WWH ::




Custom Search