The question is ambiguous: if the array may contain duplicate values, are you supposed to find the 2 largest distinct values or the two largest possibly identical values?
Your code seems to indicate you want the first approach, but you have a problem if the largest value is a[0]
. You should use an extra boolean to keep track of whether you have found a different value yet.
You should also test the return value of the different scanf()
calls and return 0 from main()
.
Here is a modified version:
#include <stdio.h>
int main(void) {
int a[10], n, i;
int largest1, largest2, has_largest2;
printf("enter number of elements you want in array: ");
if (scanf("%d", &n) != 1)
return 1;
if (n < 2) {
printf("need at least 2 elements\n");
return 1;
}
printf("enter elements: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("input error\n");
return 1;
}
}
largest1 = a[0];
for (i = 1; i < n; i++) {
if (a[i] > largest1) {
largest1 = a[i];
}
}
has_largest2 = largest2 = 0;
for (i = 0; i < n; i++) {
if (a[i] < largest1) {
if (!has_largest2) {
has_largest2 = 1;
largest2 = a[i];
} else
if (a[i] > largest2) {
largest2 = a[i];
}
}
}
if (has_largest2) {
printf("First and second largest number is %d and %d\n",
largest1, largest2);
} else {
printf("All values are identical to %d\n", largest1);
}
return 0;
}