Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

traversing, finding the max value and finding average of arrays in java

I was doing an assignment which was related to arrays. The question is:

"Complete the code segment to help Raj , find the highest mark and average mark secured by him in "s" number of subjects."

and here is the code segment which needs to be completed:

import java.util.Scanner;
public class Exercise1_5{
public static void main(String[] args) {
 Scanner input = new Scanner(System.in);
     double mark_avg;
     int result;
     int i;
     int s;
  //define size of array
   s = input.nextInt();
 //The array is defined "arr" and inserted marks into it.
  int[] arr = new int[s];   
  for(i=0;i<arr.length;i++)
  {
arr[i]=input.nextInt();
    }
//hints given:
//Initialize maximum element as first element of the array.  
//Traverse array elements to get the current max.
//Store the highest mark in the variable result.
//Store average mark in avgMarks.


//my Attempt:
/*
for (i = 1; i < arr.length; i++) 
if (arr[i] > s){
s = arr[i];}
result = s;
System.out.println(result);


double sum= 0;
for (i = 0; i < arr.length; i++) 
  sum += arr[i];
double avgMarks=sum/i;
System.out.print(avgMarks);*/

}
}
question from:https://stackoverflow.com/questions/65948431/traversing-finding-the-max-value-and-finding-average-of-arrays-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think there can be multiple ways to do. If arrays is the only data structure allowed and using the "hints given" to follow the existing code fragment, I think the algorithm can be:

  1. Store the first element in variable result.

  2. Then loop through the array and compare if the current element is larger than the variable result. If it is, then store it in variable result.

  3. The highest value will be in variable result after the iteration.

     result = arr[0];
     mark_avg = 0;
     for (int e : arr) {
         if (e > result) {
             result = e;
         }
         mark_avg += e;
     }
    
     mark_avg = mark_avg / arr.length;
    
     System.out.println("Highest mark is " + result);
     System.out.println("Average mark is " + mark_avg);
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...