135k views
4 votes
Write a program that prompts the user to enter the number of integer numbers you need to enter, then ask user to enter these integer numbers. Your program should contain an indexOfLargestElement method, which is used to return the index of the largest element in an array of integers.

User Shamilla
by
7.4k points

1 Answer

3 votes

Answer:

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner ob = new Scanner(System.in);

System.out.println("How many numbers? ");

int n = ob.nextInt();

int[] arr = new int[n];

for (int i=0; i<n; i++) {

System.out.print("Enter the number: ");

arr[i] = ob.nextInt();

}

System.out.println(indexOfLargestElement(arr));

}

public static int indexOfLargestElement(int[] arr) {

int max = arr[0];

int maxIndex = 0;

for (int i=0; i<arr.length; i++) {

if (arr[i] >= max) {

max = arr[i];

maxIndex = i;

}

}

return maxIndex;

}

}

Step-by-step explanation:

Create a method called indexOfLargestElement that takes one parameter, an array

Initialize the max and maxIndex

Create a for loop iterates throgh the array

Check each element and find the maximum and its index

Return the index

Inside the main:

Ask the user to enter how many numbers they want to put in array

Get the numbers using a for loop and put them inside the array

Call the indexOfLargestElement method to find the index of the largest element in the array

User Shaytac
by
7.9k points