How to find maximum and minimum from an array?
Problem Statement:
Consider a one-dimension integer array of 10 elements filled by a user at runtime and then find the maximum and minimum of these elements and display it.
import java.util.Scanner ; public class MaxArray { public static void main(String[] args) { Scanner sc = new Scanner(System.in) ; int[] nums = new in[10]; // populate the array for(int i=0 ; i < nums.length ; i++) { System.out.println("Enter array element at index: " + i) ; nums[i] = sc.nextInt() ; } // find the maximum of the array elements int max = nums[0] ; // put the first element in max variable for(int i=1 ; i < nums.length ; i++) { if(nums[i] > max) max = nums[i] ; } // now print the maximum element System.out.println("largest element: " + max) ; } }
Similarly you can find the smallest element by using the logic
// find the minimumof the array elements int min = nums[0] ; // put the first element in min variable for(int i=1 ; i < nums.length ; i++) { if(nums[i] < min) min= nums[i] ; } // now print the minimum element System.out.println("Smallest element: " + min) ;