Guest User

Teehee

a guest
Oct 12th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX_LENGTH 100
  5. #define SIZE 15
  6. #define FOR(i, n) for(i = 0; i < n; i++)
  7.  
  8. /**
  9.  * So sorry, my keyboard does not have the backslash key.
  10.  */
  11. void displayMessage(char* message);
  12. int getPositiveInt();
  13. int getInt();
  14. int compareInDescOrder(const void *a, const void *b);
  15. void getElement(int *array, int size);
  16. int getTheSecondLargestNumber(int *array, int size, int *secondOne);
  17.  
  18. int main() {
  19.   int array[SIZE + 1];
  20.   int secondLargestNum, isFound;
  21.  
  22.   getElement(array, SIZE);
  23.  
  24.   if(!getTheSecondLargestNumber(array, SIZE, &secondLargestNum)) {
  25.     displayMessage("All elements in this array are the same.");
  26.     return 1;
  27.   }
  28.  
  29.   printf("The second biggest element is %d\n", secondLargestNum);
  30.   return 0;
  31. }
  32.  
  33. int getTheSecondLargestNumber(int *array, int size, int *secondOne) {
  34.   int i;
  35.  
  36.   qsort(array, SIZE, sizeof(int), compareInDescOrder);
  37.   FOR(i, SIZE) {
  38.     if(array[i] != array[0]) {
  39.       *secondOne = array[i];
  40.       return 1;
  41.     }
  42.   }
  43.   return 0;
  44. }
  45.  
  46. void getElement(int *array, int size) {
  47.   int i;
  48.  
  49.   if(size < 2) {
  50.     displayMessage("It's stupid if you want to find a second largest element in the array like this.");
  51.     return;
  52.   }
  53.  
  54.   displayMessage("Please enter an array:");
  55.   FOR(i, size) {
  56.     printf("Element #%d: ", i + 1);
  57.     array[i] = getPositiveInt();
  58.   }
  59. }
  60.  
  61. int getPositiveInt() {
  62.   int res;
  63.   while((res = getInt()) < 0) {
  64.     displayMessage("Please enter a positive integer!");
  65.   }
  66.   return res;
  67. }
  68.  
  69. int getInt() {
  70.   int res;
  71.   while(scanf("%d", &res) != 1) {
  72.     displayMessage("Please enter an integer!");
  73.     while(getchar() != '\n');
  74.   }
  75.   while(getchar() != '\n');
  76.   return res;
  77. }
  78.  
  79. int compareInDescOrder(const void *a, const void *b) {
  80.   int *x = (int*)a;
  81.   int *y = (int*)b;
  82.   return *y - *x;
  83. }
  84.  
  85. void displayMessage(char* message) {
  86.   if(NULL == message) return;
  87.   printf("%s\n", message);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment