Java Reference
In-Depth Information
int
dimension=30;
int
[] v1,
v2;
v1=
new i n t
[ dimension ] ; v2=
new i n t
[ dimension ] ;
for
(
int
i=0;i
<
dimension ; i++)
{
v1 [ i ]=(
int
) (Math . random ()
∗
100) ;
// random int [0,99]
v2 [ i ]=(
int
) (Math . random ()
∗
100) ;
// random int [0,99]
}
System . out . println (
"The inner product of v1 and v2 is "
+
innerproduct(v1 ,v2)) ;
}
}
Running this program, we get:
Dim of vector x:30 Dim of vector y:30
The inner product of v1 and v2 is 80108.0
Static (class) functions may also return an array as a result of their calculation.
A typical example is the addition of two vectors that yields
another
vector of
the same dimension:
Program 4.9
Function returning an array: Addition of vectors
class
VectorAddition
{
static int
[] VectorAddition(
int
[] u,
int
[] v)
{
int
[] result=
new i n t
[u. length ];
for
(
int
i=0;i
<
u. length ; i++)
result [ i]=u[ i]+v[ i ];
return
result ;
}
public static void
main( String [ ]
args )
int
[] x=
{
1, 2, 3
}
;
int
[] y=
{
4, 5, 6
}
;
int
[] z= VectorAddition(x,y) ;
for
(
int
i=0;i
<
z . length ; i++)
System . out . print ( z [ i ]+
""
);
}
}
The following example demonstrates how one can persistently modify inside a
function the contents of an array passed as an argument. That is, this array
element swapping program shows that the values of the elements of the array
can be changed after exiting the function.
Search WWH ::
Custom Search