Search Small Ones in Java

You are given with an array, now you need to find the small and second small element from the array and then show sum of small and second small output.



import java.util.*;
public class SmallAndSecondSmall {
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
int size=0;
size=Integer.parseInt(sc.nextLine().trim());
if(size>1){
String arrayElements=sc.nextLine();
String [] array=arrayElements.split(" ");
int small=Integer.parseInt(array[0]);
int secondSmall=Integer.parseInt(array[1]);
for(int i=0;i<array.length;i++){
if(Integer.parseInt(array[i])<small){
secondSmall=small;
small=Integer.parseInt(array[i]);
}else if(Integer.parseInt(array[i])<secondSmall){
secondSmall=Integer.parseInt(array[i]);
}
}
System.out.println(small+secondSmall);
}
sc.close();
}
}
view raw SearchSmallOnes hosted with ❤ by GitHub
Input
4
1 0 -1 2

Output:
-1

Input:
7
1 2 3 4 5 6 7

Output:
3

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series