Second largest array element in C
Finding the second largest value in an array is a classic C array program. This program gives you an insight of iteration, array and conditional operators. We iteratively check each element to determine the largest and second largest element.
Algorithm
Let's first see what should be the step-by-step procedure of this program −
START Step 1 → Take an array A and define its values Step 2 → Declare largest and second as integer Step 3 → Assign first two values of array A to largest and second Step 4 → Assign the large value to largest and second largest to second Step 5 → Iterate for Array A Step 6 → If A[n] > largest, Assign largest.value to second and Assign A[n] to largest Step 7 → Else If A[n] > second, Assign A[n] to second Step 8 → Loop Terminates Step 9 → Display largest and second STOP
Pseudocode
Let's now see the pseudocode of this algorithm −
procedure largest_array(A)
Declare largest and second as integer
IF A[0] is greater than A[1] THEN
largest ← A[0]
second ← A[1]
ELSE
largest ← A[1]
second ← A[0]
ENDIF
FOR EACH value in A DO
IF A[n] is greater than largest THEN
second ← largest
largest ← A[n]
ELSE IF second is less than A[n] THEN
second ← A[n]
END IF
END FOR
Display largest and second
end procedure
Implementation
This pseudocode can now be implemented in the C program as follows −
#include <stdio.h>
int main() {
int array[10] = {101, 11, 3, 4, 50, 69, 7, 8, 9, 0};
int loop, largest, second;
if(array[0] > array[1]) {
largest = array[0];
second = array[1];
} else {
largest = array[1];
second = array[0];
}
for(loop = 2; loop < 10; loop++) {
if( largest < array[loop] ) {
second = largest;
largest = array[loop];
} else if( second < array[loop] ) {
second = array[loop];
}
}
printf("Largest - %d \nSecond - %d \n", largest, second);
return 0;
}
The output should look like this −
Largest - 101 Second - 69
array_examples_in_c.htm
Advertisements