fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. void getElements(int arr[],int n)
  4. {
  5. if(n==0 || n==1)
  6. cout<<-1<<" "<<-1<<endl; // edge case when only one element is present in array
  7. int small=INT_MAX,second_small=INT_MAX;
  8. int large=INT_MIN,second_large=INT_MIN;
  9. int i;
  10. for(i=0;i<n;i++)
  11. {
  12. small=min(small,arr[i]);
  13. large=max(large,arr[i]);
  14. }
  15. for(i=0;i<n;i++)
  16. {
  17. if(arr[i]<second_small && arr[i]!=small)
  18. second_small=arr[i];
  19. if(arr[i]>second_large && arr[i]!=large)
  20. second_large=arr[i];
  21. }
  22.  
  23. cout<<"Second smallest is "<<second_small<<endl;
  24. cout<<"Second largest is "<<second_large<<endl;
  25. }
  26. int main()
  27. {
  28. int arr[]={1,2,4,6,7,5};
  29. int n=sizeof(arr)/sizeof(arr[0]);
  30. getElements(arr,n);
  31. return 0;
  32. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Second smallest is 2
Second largest is 6