# Finding second largest number in an array

• (2 Pages)
• 1
• 2

## 16 Replies - 17730 Views - Last Post: 04 October 2009 - 01:01 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=129546&amp;s=bb9beccb50b47a359e5119bdbedfc29c&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #16 baavgai

• Dreaming Coder

Reputation: 6996
• Posts: 14,635
• Joined: 16-October 07

## Re: Finding second largest number in an array

Posted 03 October 2009 - 05:14 PM

You know, this has proven way more annoying than in initially appeared.

This is overkill, but I know it will work.
```#include <stdio.h>
#include <stdlib.h>

int first_largest(const int *a, int size) {
int i, i_first=0;

for(i=1; i<size; i++) {
if(a[i_first] < a[i]) { i_first = i; }
}
return i_first;
}

int second_largest(const int *a, int size) {
int i, i_first, i_second;

i_first = i_second = first_largest(a, size);

for(i=0; i<size; i++) {
if(a[i_first]!=a[i] && (i_first==i_second || a[i_second] < a[i])) {
i_second = i;
}
}
return i_second;
}

void printArray(int *p, int size) {
while(size-- > 0) {
printf("%d ", *p);
p++;
}
}

void test(int *a, int size) {
printArray(a, size);
printf(" : second_largest = %d\n", a[second_largest(a, size)]);
}

#define A_SIZE 4
int main() {
int a[A_SIZE] = {2,4,6,8};
int b[A_SIZE] = {44,44,22,11};
int c[A_SIZE] = {20,33,25,10};
int d[A_SIZE] = {1,2,4,4};

test(a, A_SIZE);
test(b, A_SIZE);
test(c, A_SIZE);
test(d, A_SIZE);

return 0;
}

```

### #17 brac589

Reputation: 0
• Posts: 33
• Joined: 04-March 09

## Re: Finding second largest number in an array

Posted 04 October 2009 - 01:01 AM

Who knew a simple C program could giver you such trouble.
ahaha