18. Program to Find Largest Number in an array
💡Code:
public class LargestNumber7078 { public static void main(String[] args) { // Example array int[] numbers = {15, 7, 23, 45, 9, 56, 82, 31}; // Find and print the largest number in the array int largest = findLargestNumber(numbers); System.out.println("The largest number in the array is: " + largest); } // Function to find the largest number in an array private static int findLargestNumber(int[] array) { if (array.length == 0) { throw new IllegalArgumentException("Array should have at least 1 element"); } // Assume the first element as the largest int largest = array[0]; // Iterate through the array to find the largest element for (int i = 1; i < array.length; i++) { if (array[i] > largest) { largest = array[i]; } } return largest; } }
📸Output :
.png)