In: Computer Science
Task #3 Experimenting with an array of random integers (Week
2)
Make sure that the following 3 experiments are done repeatedly by
generating a new set of integers to fill the array. For this
iterate 10 times and observe results for consistency.
• Make the array size reasonably large (say a thousand) and an even
number.
• Choose the version of nextInt() that allows you to set a cap on
the random integers generated (set it to a few thousands, but way
less than the maximum integer).
• Do the following experiments:
o Count how many integers in the array are odd and even. Are the
odd and even counts almost equal?
o Find the minimum, maximum, and average of the integers in the
array. Keep track of the minimum and maximum of the three
quantities across runs.
o Sort the array by writing an inner and an outer loop. Count the
number of times you needed to swap integers.
Code - Main.java
import java.util.*;
public class Main
{
public static void main(String[] args) {
//initialize array of 1000 number
int a[] = new int[1000];
//variable declare to be used
int
countEven=0,countOdd=0,max,min=99999,average,sum=0,i,j,swapCount=0;
//creat Random object to generate random number
Random rand = new Random();
for( i = 0 ; i <a.length;i++){
//random number will be generated from 0 to 999 and will store in
array a[]
a[i] = rand.nextInt(1000);
}
//initialize max to a[0]
max = a[0];
//for loop to get the max , min, sum , even count , odd count
for(i = 0 ; i <a.length;i++){
//count even
if(a[i]%2==0)
countEven++;
//count odd
else
countOdd++;
//get the max
if(max<a[i])
max = a[i];
//get the min
if(min>a[i])
min = a[i];
//calculate the sum
sum+=a[i];
}
//sorting the array using bubble sort alorithm
for ( i = 0; i < a.length-1; i++){
for ( j = 0; j < a.length-1-i; j++){
if (a[j] > a[j+1])
{
//count the number of swaps
swapCount++;
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
//print the result
System.out.println("Even number count is "+countEven);
System.out.println("Odd number count is "+countOdd);
System.out.println("Max number is "+max);
System.out.println("Min number is "+min);
System.out.println("Average is "+(sum/a.length));
System.out.println("Swap count for sorting "+swapCount);
}
}
Screenshots -