Thread: Please help

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    1

    Unhappy Please help

    I've been trying for days to get these functions right, but in vain. Recursion is not really my thing, and I can't figure these out at all. Any help would be greatly appreciated.

    I have to mandatorily use recurison, and the specified function header. So, that also means no loops or other function calls.

    1. int file2array(FILE *f, int a[])

    This takes in a file pointer f and a 1D array a. By calling this function in the main function, the integers in the file “unsorted1.dat (which is given)” are transferred into the elements of a 1D array a1 (one integer to each array element) declared in the main function. Do the same to transfer the integers in file “unsorted2.dat” into the elements of another 1D array a2 declared in the main function. The function returns the number of integers that are scanned from a file into an array.

    Rules: You are NOT allowed to use loops or call other functions except file2array, fscanf, and feof.

    Example: The file “unsorted2.dat” contains the numbers 7 3 14 6 such that a space separates two integers. This function will assign 7 to a2[0], 3 to a2[1], 14 to a2[2], and 6 to a2[3]. You do NOT need to worry about what the values are in the rest of the elements of array a2.



    2. int small(int a[], int n)


    This one takes in a 1D array a and the array size n. This function returns the index of the smallest integer in array a. Assume n > 0.

    Rules: You are NOT allowed to use loops or call other functions except small.


    I know that was long, but please help! Oh, I read that homework policy part, but I really don't even know where to start with these. Anyway, if this really annoyed you, very sorry.
    Last edited by nonick; 03-08-2004 at 02:12 PM.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Very well, I'm bored.
    Code:
    #include <stdio.h>
    
    int file2array(FILE *f, int a[]);
    int small(int a[], int n);
    
    int main ( void )
    {
      int a1[4];
      FILE *in = fopen ( "unsorted1.dat", "r" );
    
      if ( in != NULL ) {
        if ( file2array ( in, a1 ) )
          printf ( "Smallest value: %d\n", small ( a1, 4 ) );
        fclose ( in );
      }
    
      return 0;
    }
    
    int file2array ( FILE *f, int a[] )
    {
      if ( fscanf ( f, "%d", a ) != 1 )
        return feof ( f );
      return file2array ( f, a + 1 );
    }
    
    int small ( int a[], int n )
    {
      int sm;
    
      if ( n == 2 )
        return a[0] < a[1] ? a[0] : a[1];
      sm = small ( a + 1, n - 1 );
      return a[0] < sm ? a[0] : sm;
    }
    Now for your part. Test the program and spot the problems it has.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed