-3

This is my first question on this site.

Anyways i'm making a program that will prompt the user for how many grades to enter. Then prompt the user to enter grades between 0 and 100 and store them in a array. Finally traverse the array to find the highest grade entered and display it to the user.

The problem i'm encountering is i have no clue on how to traverse through an array to compare two indexs in a array.

import java.util.*;

public class HighestGrade {

    public static void main(String[] args) {
        //Declare and Initialize Arrays and Scanner
        Scanner scan = new Scanner(System.in);

        int num = 0;
        int[] array1;
        int highestgrade = 0;


        //Prompt user on how many grades they want to enter
        System.out.print("How many grades do you want to enter: ");
        num = scan.nextInt();
        array1 = new int[num];

        for(int i = 0; i < array1.length; i++){
            System.out.print("Enter grade out of 100: ");
            array1[i] = scan.nextInt();
        }

        //Traverse the array to find the highest grade entered

        for (int i = 0; array1[0] < array1[i]; i++){
            System.out.print("Higher");
        }

        //Display the results to the user
        System.out.print("The highest grade is " + highestgrade + ".");

        //Close scanner
        scan.close();

    }
}

2 Answers2

3

To traverse through an array you can use a loop. For loop or while loop or do while loop.

To traverse through an array and keep track of the highest value you can maintain a variable and update it after each iteration if a value larger than that is encountered.

Speaking in terms of code..

int max = arr[0];

for ( int i = 0; i < arr.length; i++) {
   if (arr[i] > max)
      max = arr[i];
}

System.out.println("Largest is : "+max);

Hope this helps..!!

Also you can use Recursion to traverse an array. But it is not recommended as it will lead to stack related issues..

Another approach to get the highest value without traversing can be seen like this..

Step 1 : Sort the array in ascending order

Step 2 : Highest value will be at the end of the array, Use it as highest value

In codes..

Arrays.sort(arr); 
System.out.println("Highest Value is : "+arr[arr.length - 1]);
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

To traverse the array you need to change your for loop like this:

for (int i = 0; i < array1.length; i++){
    // do something with array1[i]
}

Is actually what you already did to fill it. Just do the same to use its values. But there is an alternative to get the highest value, you can use Arrays.sort:

Arrays.sort(array1); // sort values in ascending order.
System.out.println(array1[array1.length-1]); // get the element in the last position (the greatest)
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50