Program to print largest and smallest element in an Array.

Here we are printing the largest and smallest element in an array using for loop.

·         First we have initialize two array variable largest and smallest with default value.

·         Now we iterate the array from 0 to arr.length size.

·         Check if largest value is less than the given array value, then initialize given array value to largest element.

·         Also else if smallest value is greater than the given array value, then initialize given array value to smallest element.

·         Print the smallest and largest elements.

				
					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 *