1. Show how to calculate the sum and average values from an array of numbers. 2.
ID: 3568435 • Letter: 1
Question
1. Show how to calculate the sum and average values from an array of numbers.
2. Show how to find if a value exists in an array of numbers; find the smallest or largest value in an
array of numbers.
3. Show an Enhanced for loop
4. Passing an array element to a method as an argument,
5. passing the entire array to a method as an argument.
6.How to declare and create an array of any object type such as Rational?
a. when you create an array, what are the initial starting values of the elements of the array?
Please show small examples for each or one for all of them
Explanation / Answer
class Rational{
}
public class Main {
public static void main(String[] args) {
int nums[] = {2,5,7,6,9};
int avg=0;
//average
for(int i=0;i<nums.length;i++){
avg+=nums[i];
}
System.out.println("Average :" + (avg/nums.length));
//if value 5 exists
for(int i=0;i<nums.length;i++){
if(5==nums[i]){
System.out.println("5 exists in array");
break;
}
}
//max and min values
java.util.Arrays.sort(nums);
System.out.println("Max Value :"+nums[nums.length-1]);
System.out.println("Min Value :"+nums[0]);
//enhanced for loop
for(int f:nums){
System.out.println(f);
}
//passing and array element as argument
showMe(nums[3]);
//passing array as argument
showArray(nums);
//creating array of object
Rational rational[] = new Rational[4];
//each element of array of type object is initialized with "null"
//that is
System.out.println(rational[2]); // will print null
// int array will initialize with 0, float with 0.0 boolen with false
float v[] = new float[5];
System.out.println(v[3]); // will print 0.0
boolean d[] = new boolean[5];
System.out.println(d[3]); // will print false
}
static void showMe(int num){
System.out.println(num);
}
static void showArray(int arr[]){
for(int f:arr){
System.out.println(f);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.