Pass as argument - a copy of the reference to the instantiated array is passed to the method. This means that any changes made to the array elements inside the method are persistent. The one exception to this is if you assign the argument to reference a different array in memory.
Q18: Put the following code in order to create a program that will declare and instantiate an array of 20 random values between 1 and 100 and then calculate and print the average of the first 10 numbers.
import java.util.*;
public class main{
public static void main (String[] args) {
---
Random r = new Random();
int [] arr = new int[20];
int sum = 0;
---
for (int i = 0; i < 20; i++) {
arr[i] = r.nextInt(100) + 1;
System.out.println("arr["+i+"] is " + arr[i]);
}
---
for (int i = 0; i < 10; i++)
---
sum += arr[i];
---
System.out.println("Avg of first 10 is " + sum/10.0);
---
}
}
Q19: Put the following code in order to create a program that will declare and instantiate an array of 20 random values between 1 and 100 and then calculate and print the average of the last n numbers.
import java.util.*;
public class main{
public static void main (String[] args) {
---
Random r = new Random();
int size = 20;
int [] arr = new int[size];
int sum = 0;
int n = r.nextInt(size);
---
for (int i = 0; i < 20; i++) {
arr[i] = r.nextInt(100) + 1;
System.out.println("arr["+i+"] is " + arr[i]);
}
---
if (n <= 0)
---
System.out.println("No numbers to average.");
---
else {
---
for (int i = 20-n; i < 20; i++)
---
sum += arr[i];
---
System.out.println("Avg of last n is " + (sum * 1.0)/n);
---
}
---
}
}