fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int secondSmallest(int arr[],int n)
  4. {
  5. if(n<2)
  6. return -1;
  7. int small = INT_MAX;
  8. int second_small = INT_MAX;
  9. int i;
  10. for(i = 0; i < n; i++)
  11. {
  12. if(arr[i] < small)
  13. {
  14. second_small = small;
  15. small = arr[i];
  16. }
  17. else if(arr[i] < second_small && arr[i] != small)
  18. {
  19. second_small = arr[i];
  20. }
  21. }
  22. return second_small;
  23. }
  24. int secondLargest(int arr[],int n)
  25. {
  26. if(n<2)
  27. return -1;
  28. int large=INT_MIN,second_large=INT_MIN;
  29. int i;
  30. for (i = 0; i < n; i++)
  31. {
  32. if (arr[i] > large)
  33. {
  34. second_large = large;
  35. large = arr[i];
  36. }
  37.  
  38. else if (arr[i] > second_large && arr[i] != large)
  39. {
  40. second_large = arr[i];
  41. }
  42. }
  43. return second_large;
  44. }
  45.  
  46. int main() {
  47. int arr[]={1,2,4,7,7,5};
  48. int n=sizeof(arr)/sizeof(arr[0]);
  49. int sS=secondSmallest(arr,n);
  50. int sL=secondLargest(arr,n);
  51. cout<<"Second smallest is "<<sS<<endl;
  52. cout<<"Second largest is "<<sL<<endl;
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5240KB
stdin
Standard input is empty
stdout
Second smallest is 2
Second largest is 5