Header Ads Widget

Write a program to find the second largest number in an array of integers.

 Write a program to find the second largest number in an array of integers

Algorithm:-

1. Declare an array of integers and initialize it with some values. 2. Initialize largest = array[0] and secondLargest = array[0] 3. for i = 1 to size of array - 1 do 4. if array[i] > largest then 5. set secondLargest = largest 6. set largest = array[i] 7. else if array[i] > secondLargest and array[i] != largest then 8. set secondLargest = array[i] 9. end if 10. end for 11. Print the value of secondLargest.

Code(C++):-

#include <iostream>
using namespace std;

int main() {
  int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
  int size = sizeof(arr)/sizeof(arr[0]);
  int largest = arr[0], secondLargest = arr[0];

  for(int i = 1; i < size; i++) {
    if(arr[i] > largest) {
      secondLargest = largest;
      largest = arr[i];
    }
    else if(arr[i] > secondLargest && arr[i] != largest) {
      secondLargest = arr[i];
    }
  }

  cout << "Second largest number in the array is: " << secondLargest << endl;

  return 0;
}


Output:-

Second largest number in the array is: 90


Questions About Accenture:-

Recommended Post :-