9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex32.c (1338B)
   1 //    Calculates the max or min in an array of numbers;
   2 //    of type int;
   3 
   4 #include <stdio.h>
   5 #include <stdlib.h>
   6 #include <limits.h>
   7 
   8 #define MAX_ELEM                10
   9 #define NO_ARGUMENT_ENTERED        1 
  10 #define EXTREMO_ARGUMENT        1
  11 
  12 typedef enum {
  13     MAXIMUM,
  14     MINIMUM
  15 } extreme_t;
  16 
  17 typedef enum {
  18     OK,
  19     ERROR_INVOCATING_PROGRAM,
  20     ERROR_NULL_POINTER
  21 } status_t;
  22 
  23 status_t validate_arguments (int argc, char ** argv);
  24 
  25 int main (int argc, char * argv[])
  26 {
  27     size_t i;
  28     int vector[MAX_ELEM] = {9, 10, 25, 31, 9, 5, 11, 46, 50, 20};
  29     extreme_t extremo;
  30     status_t st; 
  31 
  32     if((st = validate_arguments(argc, argv)) != OK)
  33         return st;
  34 
  35     extremo = atoi(argv[EXTREMO_ARGUMENT]);
  36     if(extremo == MAXIMUM) {
  37     //    Find maximum element in array;
  38         int maximum;
  39         for(i = 0, maximum = INT_MIN; i < (sizeof(vector)/sizeof(vector[0])); i++)
  40             if(vector[i] > maximum)
  41                 maximum = vector[i];
  42         
  43         printf("%d\n", maximum);
  44     } else if (extremo == MINIMUM){
  45     //    Find minimum element in array;
  46         int minimum;
  47         for(i = 0, minimum = INT_MAX; i < (sizeof(vector)/sizeof(vector[0])); i++)
  48             if(vector[i] < minimum)
  49                 minimum = vector[i];
  50 
  51         printf("%d\n", minimum);
  52     }
  53     return 0;
  54 }
  55 
  56 status_t validate_arguments (int argc, char ** argv) {
  57     if(argc == NO_ARGUMENT_ENTERED)
  58         return ERROR_INVOCATING_PROGRAM;
  59 
  60     else if (argv == NULL)
  61         return ERROR_NULL_POINTER;
  62 
  63     else return OK;
  64 }
  65