I need to find 3 largest numbers in an array and then add them together.
For example: Input: 3 4 7 10 11 16 16 23 26 Output: The sum of the 3 largest even numbers are: 16, 16, 26. The sum is 58
In my code, I'm getting weird outputs like "16, 1245782582792, 1".
Note: I can only use ifs/else, for/while loops, and arrays for this.
#include <stdio.h>
#define MAX_NUMBERS 13
int main(void) {
int nNumbers, i;
int even_sum;
int array[MAX_NUMBERS];
int greatest1, greatest2, greatest3;
//Reading the numbers
scanf("%d", &nNumbers);
for(i = 0; i < nNumbers; i++) {
scanf("%d", &array[i]);
}
//Finding largest even numbers
greatest1 = array[0];
for(i = 0; i <= MAX_NUMBERS; i++){
if(array[i] > greatest1 && array[i] % 2 == 0){
greatest1 = array[i];
}
}
greatest2 = array[0];
for(i = 0; i <= MAX_NUMBERS; i++){
if(array[i] > greatest2 && array[i] % 2 == 0 && array[i] != greatest1){
greatest2 = array[i];
}
}
greatest3 = array[0];
for(i = 0; i <= MAX_NUMBERS; i++){
if(array[i] > greatest2 && array[i] % 2 == 0 && array[i] != greatest1 && array[i] != greatest2){
greatest2 = array[i];
}
}
even_sum = greatest1 + greatest2 + greatest3 + 2;
printf("The largest even numbers are %d, %d, %d. The sum is %d.\n", greatest1, greatest2, greatest3, even_sum);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire