Skip to main content

Second largest element using pointer

Short answer

Read array via pointer. Track first largest and second (found flag). In one pass, if element > first, shift first to second; else if element < first and (not found or > second), update second. Print second largest if found, else indicate all equal. Example output: Largest = 89, second largest = 45.

Write a program in C to find second largest elements from an array containing N elements using concept of pointer.

Logic. The array is read through a pointer p (p + i gives the address of element i, and *(p + i) its value). first starts as the first element, and the flag found shows whether a second, different value has been seen yet. For each remaining element v:

  • if v is greater than first, the old first becomes second and v becomes first;
  • otherwise, if v is less than first and (no second exists yet, or v is greater than second), v becomes second;
  • a value equal to first is ignored, so a repeated largest value is not counted as the second largest.

This takes only one pass over the array. If all the elements are equal, there is no second largest.

#include <stdio.h>

int main(void)
{
    int a[100], n, *p = a;
    printf("Enter N: ");
    if (scanf("%d", &n) != 1 || n < 2 || n > 100) {
        printf("N must be between 2 and 100\n");
        return 1;
    }
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++)
        scanf("%d", p + i);

    int first = *p, second = 0, found = 0;   /* found = 1 once a second distinct value exists */
    for (int i = 1; i < n; i++) {
        int v = *(p + i);
        if (v > first) {
            second = first;
            first = v;
            found = 1;
        } else if (v < first && (!found || v > second)) {
            second = v;
            found = 1;
        }
    }
    if (found)
        printf("Largest = %d, second largest = %d\n", first, second);
    else
        printf("All elements are equal: no second largest\n");
    return 0;
}

Sample run (12 45 7 89 45 23)

Input: 6 12 45 7 89 45 23

Enter N: Enter 6 elements: Largest = 89, second largest = 45

With the input 3 89 89 45 the output is Largest = 89, second largest = 45, because the repeated 89 is not counted twice.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →