/* A program to read n numbers, compute their maximum, minimum, and average,
 * and to print a specified jth item.
 * This code repeats the program max-min.c, except that standard input
   is redirected to the file "data".
 */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main (void)
{    int j, n;
     double max, min, sum;

     int fid;
     fid = open ("data", O_RDONLY);  
          /* open file for read only */
    
     /* set standard input to file */
     if (dup2(fid, STDIN_FILENO) != STDIN_FILENO)
       { perror("dup2 error for standard input");
       exit(1);
       }

     close(fid); /* close fid, as standard in now set to file */

     printf ("Program to process real numbers.\n");
     printf ("Enter number of reals: ");
     scanf ("%d", &n);

     {  /* start new block, where new array may be declared */
        double a[n];  /* declare array of n values, with subscripts 0, ..., n-1
                         While ANSI C allows only constant array sizes,
                         some compilers allow variables in the specification
                         of array size, as shown here                   */

        printf ("Enter %d numbers: ", n);
        for (j = 0; j < n; j++)
             scanf ("%lf", &a[j]); /* subscripts given in brackets [ ]  */

        sum = max = min = a[0];    /* right to left assignment operator */

        for (j = 1; j < n; j++)
           { if (a[j] > max)
                max = a[j];
             if (a[j] < min)
                min = a[j];
             sum += a[j];
           }
        printf ("Maximum:  %5.2f\n", max);
        printf ("Minimum:  %5.2f\n", min);
        printf ("Average:  %5.2f\n\n", sum/n);

        printf ("Enter the index (1..n) of the number to be printed: ");
        scanf  ("%d", &j);
        printf ("The %d th number is %.2f\n", j, a[j-1]);
     } /* end of array block */

     return 0;
}

