- 2074 Asoj · 4 marks
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
vis greater thanfirst, the oldfirstbecomessecondandvbecomesfirst; - otherwise, if
vis less thanfirstand (nosecondexists yet, orvis greater thansecond),vbecomessecond; - a value equal to
firstis 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)
Related questions
- Accessing array elements using pointer · Computer Programming, chapter 9
- Reverse array and display via pointer · Computer Programming, chapter 9
- Pass array; largest and smallest · Computer Programming, chapter 7
- Pass 2D array; largest and smallest · Computer Programming, chapter 7
- Function returning largest of array · Computer Programming, chapter 7
- Relation between array and pointer · Computer Programming, chapter 9 · asked 5×
- Stored program concept and processing cycle · Microprocessor, chapter 1 · asked 6×
- Two-element array and end fire pattern · Propagation and Antenna, chapter 2
- Simple program illustrating OOP concept · Object Oriented Programming, chapter 1
- Two-element array: broadside and end fire · Propagation and Antenna, chapter 2