In: Computer Science
Maximum value and its index in an array
java program that:
Given below is the code for the question. Please do rate the
answer if it helped. Thank you.
import java.util.Random;
import java.util.Scanner;
public class FindMax {
public static void main(String[] args) {
int n;
if(args.length != 1) {
System.out.println("No. of elements not specified as command line
argument");
Scanner input =
new Scanner(System.in);
System.out.print("How many elements? ");
n =
input.nextInt();
}
else {
n =
Integer.parseInt(args[0]);
}
int[] arr = new int[n];
Random rand = new Random();
for(int i = 0; i < n; i++)
{
arr[i] = 1 +
rand.nextInt(100);
}
//find the max and its index
int maxIndex = 0;
for(int i = 1; i < n; i++)
{
if(arr[i] >
arr[maxIndex]){
maxIndex = i;
}
}
System.out.println("The array
elements are ");
System.out.print("{");
for(int i = 0; i < n; i++)
{
if(i != 0)
System.out.print(", ");
System.out.print(arr[i]);
}
System.out.println("}");
System.out.println("The max element
is " + arr[maxIndex] + " at index " + maxIndex);
}
}