Untitled
user_9781718
plain_text
a year ago
1.0 kB
8
Indexable
#include <iostream> using namespace std; int main() { int n; cout << "Enter the size of the array: "; cin >> n; int arr[n]; cout << "Enter the elements of the array: "; for (int i = 0; i < n; i++) { cin >> arr[i]; } // Find the second largest and smallest elements using a single traversal int largest = arr[0], secondLargest = INT_MIN; int smallest = arr[0], secondSmallest = INT_MAX; for (int i = 1; i < n; i++) { if (arr[i] > largest) { secondLargest = largest; largest = arr[i]; } else if (arr[i] > secondLargest && arr[i] != largest) { secondLargest = arr[i]; } if (arr[i] < smallest) { secondSmallest = smallest; smallest = arr[i]; } else if (arr[i] < secondSmallest && arr[i] != smallest) { secondSmallest = arr[i]; } } cout << "Second largest element: " << secondLargest << endl; cout << "Second smallest element: " << secondSmallest << endl; return 0; }
Editor is loading...
Leave a Comment