The code defines a Java program to find the largest number in an array of integers.
The program starts by initializing a Scanner object to read input from the user. Then it creates an array of 20 integers named numbers
.
The program then prompts the user to enter the number of values they want to store in the array. This value is stored in the quantity
variable.
A for loop is then used to read quantity
numbers from the user and store them in the numbers
array.
After all the numbers have been entered, the Scanner object is closed.
Next, the variable currentNumber
is initialized with the first number in the numbers
array. A for loop is then used to iterate over the numbers
array, starting from the second position (i=1
) and ending at i=quantity
. In each iteration, the code checks if the current value of currentNumber
is less than the value of the current array element (numbers[i]
). If it is, then the value of currentNumber
is updated to be the value of numbers[i]
.
After the loop has completed, the code prints out the value of currentNumber
, which is the largest number in the array.
import java.util.Scanner;
public class LargestNumberInArray {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] numbers = new int[20];
int i = 0, currentNumber, quantity;
System.out.print("How many numbers do you want to store in array? (1 - 20): " );
quantity = reader.nextInt();
// Store numbers in array (user input)
for(i = 0 ; i < quantity ; i++) {
System.out.println("Please enter a number: ");
numbers[i] = reader.nextInt();
}
reader.close();
currentNumber = numbers[0];
// loop over array and store largest number in first array position
for(i = 1; i < quantity; i++) {
if(currentNumber < numbers[i]) {
currentNumber = numbers[i];
}
}
System.out.println("Largest number in array is: " + currentNumber);
}
}
How many numbers do you want to store in array? (1 - 20): 5
Please enter a number:
1
Please enter a number:
2
Please enter a number:
3
Please enter a number:
4
Please enter a number:
5
Largest number in array is: 5