### Required knowledge

Basic C programming, Array### Algorithm to find second largest element

The basic logic behind this problem can be divided in three steps:- First assume that
**max1**and**max2**are the first element of array (where**max1**represents first maximum and**max2**represents second maximum element) and after that run a loop from second element till**N**(where**N**is the size of the array). - If the current element of array is greater than
**max1**then copy the value of**max1**to**max2**as a new maximum has been found. Also copy the value of current array element to**max1**. - Else if the current array element is greater than
**max2**but is less than**max1**then also copy the value of current array element to**max2**.

Algorithm to find second largest element in an array%%Input :{Array in which largest is to be found}arr{Size of the array}NBegin:max1←arr[0];max2←arr[0];Fori← 1toNdoIf(arr[i] >max1) thenmax2←max1;max1←arr[i];End ifElse if(arr[i] >max2) thenmax2←arr[i];End ifEnd forEnd

### Program

/** * C program to find second largest number in an array */ #include <stdio.h> #include <limits.h> //For INT_MIN #define MAX_SIZE 1000 int main() { int arr[MAX_SIZE], N, i; int max1, max2; /* * Reads size and elements in the array */ printf("Enter size of the array (1-1000): "); scanf("%d", &N); printf("Enter elements in the array: "); for(i=0; i<N; i++) { scanf("%d", &arr[i]); } max1 = max2 = INT_MIN; /* * Checks for first largest and second largest till N */ for(i=0; i<N; i++) { if(arr[i] > max1) { /* * If current element of the array is first largest * then make current max as second max * and then max as current array element */ max2 = max1; max1 = arr[i]; } else if(arr[i] > max2) { /* * If current array element is less than first largest * but is greater than second largest then make it * second largest */ max2 = arr[i]; } } printf("First largest = %d\n", max1); printf("Second largest = %d", max2); return 0; }

Output

Enter size of the array (1-1000): 10

Enter elements in the array: -7 2 3 8 6 6 75 38 3 2

First largest = 75

Second largest = 38

Enter elements in the array: -7 2 3 8 6 6 75 38 3 2

First largest = 75

Second largest = 38

Happy coding ;)

### You may also like

- C program to find maximum between two numbers.
- C program to find maximum between three numbers.
- C program to find maximum and minimum element of an array.
- C program to count total number of duplicate elements in an array.
- C program to delete all duplicate elements from an array.
- C program to count total number of notes in a given amount.
- C program to print all unique elements in an array.
- C program to perform scalar matrix multiplication.
- C program to multiply two matrices.
- C program to find transpose of a matrix.
- C program to interchange diagonals of a matrix.
- C program to check Identity or Unit matrix.