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>
There are a few problems here:
You should only examine the array entries that are defined. Instead, you are looking at the entire array, including the undefined portion from nNumbers
through MAX_NUMBERS-1
. You will likely pick up garbage values there. Change your for
loops to:
for (i = 0; i < nNumbers; i++)
You are initializing greatest1
, etc. to the first number in the array. That doesn't work if the number is odd and happens to be large enough to block the even number you're looking for.
If one of the largest even numbers occurs more than once, you will ignore the duplicates. For instance, if the largest number is 1000, and it occurs three times, you probably want to add all three and return 3000. You can fix this by keeping track of the indices you have chosen, and only rejecting a duplicate if the index matches, rather than the value.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments