-5

I have homework in which you have to find the two biggest numbers in n elements (the number of elements is 'a') But I cant seem to find the second biggest number. Can you please help me? Thanks

#include<stdio.h>

int main()
{
int a, c, i; 
int b; 
b=0;
c=0;

scanf(" %d",&a);
for(i=2;i<=a;i++) //find the biggest number
{
scanf("%d",&c);

if(b<c)
b=c;     
}
if (a > c) //Here I cant find my second biggest number
c = a;
printf("%d %d", b, c);      
return 0;
}
cdonts
  • 9,304
  • 4
  • 46
  • 72

1 Answers1

1

Here is a small program that will find the largest and second largest value in an array.

The relevant bits to take from this is that it scans through the array of elements one at a time and compares it with its current "largest value". If the value in the array is larger then it stores that as the new largest value. Before storing that it copies the old largest value as the new "second largest value".

[Edit: I have updated the algorithm to handle the case where the second largest value would never be set. For example with an input set of {2,1}. Additionally I updated it to handle negative numbers.]

#include <stdio.h>
#include <limits.h>

int myArray [] = {2,5,9,1,7,13,3,11};

#define NumElements( array ) sizeof(array)/sizeof(array[0])

int main(int argc, const char * argv[])
{

    int i;
    int largest = INT_MIN;
    int secondLargest = INT_MIN;

    for( i=0; i<NumElements(myArray); i++ )
    {
        if( myArray[i] > largest )
        {
            secondLargest = largest;
            largest = myArray[i];
        }
        else if( myArray[i] > secondLargest )
        {
            secondLargest = myArray[i];
        }
    }

    printf( "largest: %d\n", largest );
    printf( "second largest: %d\n", secondLargest );

    return 0;
}
waterjuice
  • 829
  • 5
  • 14
  • I have updated the algorithm to handle the case where the second largest value would never be set. For example with an input set of {2,1}. Additionally I updated it to handle negative numbers. – waterjuice Oct 13 '15 at 00:08
  • Much nicer. A minor thought: testing against the `secondLargest` first has the advantage that typically each time through the loop, only 1 test needed. – chux - Reinstate Monica Oct 13 '15 at 00:18
  • Can you change it for the program to detect the biggest two numbers in n elements? Like you can input any 7 numbers that you want – Lalo Perez Cortes Oct 13 '15 at 12:22