my question is that I need to find the second largest value from my array but I am getting the same value which is equal to the first value. please help
int[] nums = { 50, 6, 60, 70, 80, 90, 9, 150, 2, 35 }; int max = 0; int secmax = 0; for (int x = 0; x < nums.length; x++) { if (nums[x] > max) max = nums[x]; if (nums[x] > secmax && secmax != max) secmax = nums[x]; } System.out.println("1st H value: " + max); System.out.println("2nd H Value: " + secmax);
Advertisement
Answer
your mistake is the conditions in the loop use this code:
public class Main{ public static void main(String[] args){ int[] nums = { 6, 9, 11, 1, 10 }; int max = Integer.MIN_VALUE; int secmax = Integer.MIN_VALUE; for(int x=0; x<nums.length; x++) { if(nums[x]>max ) { secmax = max; max=nums[x]; }else if(nums[x]>secmax){ secmax=nums[x]; } } System.out.println("1st H value: " + max); System.out.println("2nd H Value: " + secmax); } }