I have an array of integers and I’m trying to find which one is the highest and set a new integer to the highest ones value. I’m very new to C, I literally just started learning it.
There is probably some kind of logical problem with what I’m doing but I haven’t been able to spot it yet. so…
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > my_array[i++]) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
else {
if (my_array[i++] > highest_int) {
highest_int = my_array[i++]
}
}
}
So I loop through my array 4 times (4 elements) and I look at the iteration value and the next one and if the iteration value is highest I check it’s also higher than the current value of the current ‘highest integer’ and if it is I set the current highest integer to the new highest value. If the value after the iteration value is higher I do the same thing but with that value instead.
That’s what went through my head when I wrote this but when I enter 4 values it always comes out with the 3rd value in the array. No matter what I set those values to.
Can anyone tell me why?
Thanks a lot.
You’re making this way more complicated than it really is 🙂 Furthermore, you’re writing
i++in too many places; each timei++gets executed you’re skipping over an array entry, which is probably not what you want.Also, there’s no need to compare to the previous value. Just compare to the highest one you’ve seen so far.
Here’s a fixed version, just by deleting code, nothing changed or added:
Note that this incorrectly reports 0 if all numbers in the array are negative. Start off
highest_int = INT_MINin case you need to handle those correctly, or useunsigned int.