DEV Community

Cover image for Print The Second Largest Element of The Array For Beginners logic....
Roshan Shambharkar
Roshan Shambharkar

Posted on

Print The Second Largest Element of The Array For Beginners logic....

To print Second largest Element form an array you need to have basic understanding of the array data structure to learn more about array data structure you can refer this article

To find second largest Element in an arrat follow below steps mentioned

Step 1 Store First largst Number and second largest number in Integer.MIN_VALUE (is a constant in the Integer class of java.lang package that specifies that stores the minimum possible value for any integer variable in Java. The actual value of this is -2^31 = -2147483648 )

for e.g int FirstlargestNumber = Integer.MIN_VALUE;
int SecondlargestNumber = Integer.MIN_VALUE;

Step 2 Traverse through an array using for loop.
For e.g for(int i = 0; i<a.length; i++)

Step 3 compare values in the array with FirstlargestNumber using if statements

For e.g : if(a[i] > FirstlargestNumber )
FirstlargestNumber = arr[i];

Step 4 : Now again run a loop for SecondlargestNumber
for e.g: for(int i = 0; i<a.length; i++);

Step 5: And then comparing using if statement

for eg : if (a[i] > secondlargest && a[i] < firstlargest)
{
second_largest = a[i];
}
}
System.out.print(second_largest );

Now read complete code below line by line to get clarify

class Test {
public static void main(String args[]){
int firstlargestNumber = Integer.MIN_VALUE;
int secondLargestNumber = Integer.MIN_VALUE;
for(int i = 0; i<a.length; i++) {
if(a[i] > firstlargestNumber) {
firstlargestNumber = a[i];
}
}
for(int i = 0; i<a.length; i++) {
if(a[i] > secondLargestNumber && a[i]< firstlargestNumber) {
a[i] = secondLargestNumber;
}
}
System.out.println(secondLargestNumber);
}
}

Top comments (0)