Write a JAVA program that declares an array numList of 100 elements of type int.
ID: 3767099 • Letter: W
Question
Write a JAVA program that declares an array numList of 100 elements of type int. Initialize the array with random numbers between 1 and 500. Then write three user-defined methods as follows.
-Write a method that takes as its parameter as int array, and outputs the array so that 10 elements per line are printed.
-Write a method that takes as its parameter as int array, and returns the average of the elements in the array as a double.
-Write a method that takes as its parameter as int array, and returns the index of the smallest element in the array.
Then in main method, call these user-defined methods with appropriate parameters and output the results.
Explanation / Answer
import java.util.*;
class arr_numList
{
public static void print(int a[])
{
int i,n=0;
for(i=0;i<100;i++)
{
if(n==10)
{
System.out.println();
n=0;
}
else
{
System.out.print
(a[i]+",");
n++;
}
}
}
public static double aver(int a[])
{
int i,sum=0;
for(i=0;i<100;i++)
{
sum=sum+a[i];
}
return sum/100;
}
public static int min(int a[])
{
int b=0,i,m=a[0];
for(i=0;i<100;i++)
{
if(a[i]<m)
{
m=a[i];
b=i;
}
}
return b;
}
public static void main(String args[])
{
int numList[]=new int[100];
int i;
Random ra= new Random();
for(i=0;i<100;i++)
{
numList[i]=(ra.nextInt
(500)+1);
}
print(numList);
double av=aver(numList);
System.out.println("Average ="+av);
int ind=min(numList);
System.out.println("Index of Smallest
element is = "+ind);
}
}