Reputation: 17
I'm currently learning Java and while I'm able to find the largest number I'm stuck on how to find it's location. Any help would be greatly appreciated!
import java.util.Random;
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = 0;
for (i = 0; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
}
}
System.out.println("\n\nThe largest value is
"+largeNumb);
}
}
Upvotes: 0
Views: 194
Reputation: 1
import java.util.Random;
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = array_1[0];
int index = 0;
for (i = 1; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
index = i;
}
}
System.out.println("\n\nThe largest value is :" + largeNumb + " and it's index is: " + index);
}
}
Upvotes: 0
Reputation: 66
You should get an another variable for the index = 0
and then put it inside the if statement and make it equal to index = i;
. After the loop ends the largest value index would be stored here.
Upvotes: 0
Reputation: 11
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = 0;
int index = 0;
for (i = 0; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
index = i;
}
}
System.out.println("The largest value is " + largeNumb + " and it's location is" + index);
}
}
Upvotes: 1
Reputation: 222
you can make an int index=0 in the loop where you check if the number is bigger in the body of the if make infex=i. This way you will always have both the value and the index of the largest numnber.
Upvotes: 0