Skip to content

Instantly share code, notes, and snippets.

@ryzokuken
Last active October 23, 2016 12:04
Show Gist options
  • Save ryzokuken/2cad3676696afc509c1d003a807f4ea3 to your computer and use it in GitHub Desktop.
Save ryzokuken/2cad3676696afc509c1d003a807f4ea3 to your computer and use it in GitHub Desktop.
Finds the sum of five maximum numbers in a 3x3 matrix and print the output to STDOUT
/***************************************************************
* maxfive.c : Ujjwal Sharma *
* This program finds the five maximum numbers *
* in a 3x3 matrix and prints its sum to STDOUT *
***************************************************************/
#include <stdio.h>
int main() {
int elems = 0, i, j, max[5], sum = 0; /* elems is the number of elements in the max array */
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
int input, index; /* as we don't need to store input permanently */
scanf("%d", &input);
for (index = 0; index < elems && input > max[index]; index++); /* Find out the position input is supposed to be in */
if (elems < 5) { /* If the elements inside max are fewer than 5 */
int k;
for (k = elems; k > index; k--) { /* Push all elements more than input towards the right */
max[k] = max[k - 1];
}
max[index] = input;
elems++;
} else if (index > 0) { /* If the max array is full, we only need to add an element if it's greater than the first element*/
int k;
for (k = 0; k < index - 1; k++) { /* Push all elements less than input towards the left, effectively losing the first*/
max[k] = max[k + 1];
}
max[index - 1] = input;
}
}
}
for (i = 0; i < 5; i++) {
sum += max[i];
}
printf("Sum of 5 max numbers is %d\n", sum);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment