Java Program to print the largest and smallest element in an array?

Here we iterate the array and check where given array value is greater than initialize largest value.if it greater then initialize value to largest element.then it is largest element in array.also check where smallest array is greater than given array.

				
					public class LargestAndSmallestArray {
	public static void main(String[] args) {
		int arr[] = { 12, 10, 54, 178, 7 };
		int largest = arr[0];
		int smallest = arr[0];
		int index = 0;
		int small = 0;
		for (int i = 0; i < arr.length; i++) {
			if (largest < arr[i]) {
				largest = arr[i];
				index = i;
			} else if (smallest > arr[i]) {
				smallest = arr[i];
				small = i;
			}
		}
		System.out.println("Largest element:- " + largest);
		System.out.println("Smallest element:- " + smallest);
	}
}

				
			

Output :-
Largest element:- 178
Smallest element:- 7

Leave a Comment

Your email address will not be published. Required fields are marked *