Find the largest element in an array.
#include <stddef.h>
int largest(const int *a, size_t n) /* n >= 1 */
{
int max = a[0]; /* start with an element, not 0 */
for (size_t i = 1; i < n; i++)
if (a[i] > max) max = a[i];
return max;
}
Points: initialise with a[0] (or INT_MIN) so all-negative arrays work; O(n), one pass; to find min and max together with fewer comparisons, process elements in pairs (about 1.5n comparisons instead of 2n).