Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active April 21, 2017 19:01
Show Gist options
  • Save softwarespot/0b2aceaf6f5b880deae4 to your computer and use it in GitHub Desktop.
Save softwarespot/0b2aceaf6f5b880deae4 to your computer and use it in GitHub Desktop.
A very simple min and max example in C
#include <stdio.h>
int main(void) {
int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
int max = data[0];
int min = data[0];
// Obtain the size of the array by obtaining the number of bytes of the array divided by the size of the first element
// e.g. 4 bytes for an int would mean the size of the array is 4 * 10 = 40, then divided by the size of an int i.e. 4 is 40 / 4 therefore 10 items
int size = sizeof(data) / sizeof(data[0]);
// I have been told it's best to declare i outside of the loop in old versions of C, though in new 'int i = 0' is fine
for (i = 1; i < size; i++) {
// Assume the new maximum
if (data[i] > max) {
max = data[i];
}
// Assume the new minimum
if (data[i] < min) {
min = data[i];
}
}
// Print to the console
printf("%i\n", max);
printf("%i\n", min);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment