Thread: Arrays and Functions

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    36

    Arrays and Functions

    I wrote a program to scan a Student's ID # from a file into one array, and scan their Mark from the same file into another parallel array. My code below works fine, but once I had written it all, I realised that I needed to make a function (called "getData" or something) to input the data from the file into the arrays and print the data. I did this all in main instead.

    I'm just having trouble trying to figure out how to put this step into a function. Below is my working code.

    Code:
    /*This program will input data into two parallel arrays from scores.txt.
     *It will them print out the student's score according to their ID number.
     *
     *Input:
     *Student Number
     *
     *Outputs:
     *Student Number
     *Mark of Student
     */
     
    #include <stdio.h>
    #define MAXIMUM 100
    #define SENTINEL -99
    
    /*Function Prototypes*/
    int searchArray (const int iArray[], int iNum, int iTarget);
    
    int main (void)
    {
    	int iId[MAXIMUM], iScore[MAXIMUM];     /*Arrays*/
    	int iNum, iTarget, iStatus, iPosition; /*Array Parameters*/
    	FILE *inp;
    	
    	inp = fopen("C:/Documents and Settings/Administrator/Desktop/scores.txt", "r");
    	
    	if (inp == NULL)
    	{
    		printf("Unable to open file!\n");
    		return(-1);
    	}
    		
    	iNum = 0;
    	iStatus = fscanf(inp, "%d %d", &iId[0], &iScore[0]);
    	while (iStatus != EOF)
    	{
    		iNum++;
    		iStatus = fscanf(inp, "%d %d", &iId[iNum], &iScore[iNum]);
    	}
    
    	if (iNum > MAXIMUM)
    	{
    		printf("Too much input data!\n");
    		return (-1);
    	}
    
    
    	printf("Enter a student number (-99 to quit): ");
    	scanf("%d", &iTarget);
    	while (iTarget != SENTINEL)
    	{
    		iPosition = searchArray (iId, iNum, iTarget);
    		if (iPosition == -1)
    		{
    			printf ("Not in Array!\n");
    			return(-1);
    		}
    
    		printf("Student number: %d\n", iId[iPosition]);
    		printf("Mark:           %d%%\n\n", iScore[iPosition]);
    		printf("Enter a student number (or -99 to quit): ");
    		scanf("%d", &iTarget);
    	}
    
    	fclose(inp);
    
    
    
    	return (0);
    }
    
    
    
    
    /*****FUNCTIONS*****/
    
    
    
    
    int searchArray (const int iId[], int iNum, int iTarget)
    {
    	int iFound, iPosition;
    	
    	/*Assume target has not been found*/
    	iFound = 0;
    	/*Loop until either target is found or we are at end of data*/
    	iPosition = 0;
    	while (iFound == 0 && iPosition < iNum)
    	{
    		if (iId [iPosition] == iTarget)
    		{
    			iFound = 1;
    		}
    		else
    		{
    			iPosition++;
    		}
    	}
    	if (iFound == 0)
    	{
    		return (-1);
    	}
    	else
    	{
    		return (iPosition);
    	}
    
    }

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    just create the function and copy the code into it. I didn't compile this so it may contain missing variables which you need to add yourself.
    Code:
    int getData(int iId[], int Score[])
    {
       // put code here to read the file
    	FILE *inp;
    	
    	inp = fopen("C:/Documents and Settings/Administrator/Desktop/scores.txt", "r");
    	
    	if (inp == NULL)
    	{
    		printf("Unable to open file!\n");
    		return -1;
    	}
    		
    	iNum = 0;
    
    	while( fscanf(inp, "%d %d", &iId[iNum], &iScore[iNum]) == 2)
    	{
    		iNum++;
    	}
            fclose(inp);// close the file
          return iNum; // return number of ints read
    }
    Last edited by Ancient Dragon; 11-03-2005 at 09:06 AM.

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    Yes, but how do I define the function in "main"?

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    you don't put it INSIDE main, but either above or below it.

    Code:
    int getData(int iId[], int Score[])
    {
      // blabla
    }
    
    
    int main (void)
    {
        int iId[MAXIMUM], iScore[MAXIMUM];     /*Arrays*/
    
       // now call the function getData
       getData(iId,iScore);
    
    
    }
    Last edited by Ancient Dragon; 11-03-2005 at 10:02 AM.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    if (iNum > MAXIMUM)
    {
        printf("Too much input data!\n");
        return (-1);
    }
    A similar check must be made a part of your while loop that reads the data into your array otherwise you run the risk of overrunning the bounds of those arrays.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    I guess I was just wondering how to "call" the function in main.

    Code:
    int main(void)
    {
         getData(iId,iScore);
         etc...
    }
    Is this right?
    Why no square brackets after the iId and iScore arrays? Why won't getData(iId[], iScore[]); work?

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You use brackets when you want to access a specific element. You use the name of the array when you're talking about the whole thing.


    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    I have made the changes you suggested, and my program will now succesfully compile and build, but it will not run.
    Here is the new code:

    Code:
    /*This program will input data into two parallel arrays from scores.txt.
     *It will them print out the student's score according to their ID number.
     *
     *Input:
     *Student Number
     *
     *Outputs:
     *Student Number
     *Mark of Student
     */
     
    #include <stdio.h>
    #define MAXIMUM 100
    #define SENTINEL -99
    
    /*Function Prototypes*/
    int getData(int iId[], int Score[]);
    int searchArray (const int iArray[], int iNum, int iTarget);
    
    int main (void)
    {
    	int iId[MAXIMUM], iScore[MAXIMUM];     /*Arrays*/
    	int iNum, iTarget, iPosition; /*Array Parameters*/
    	
    	/*Call Function to get data*/
    	getData(iId, iScore);
    
    	if (iNum > MAXIMUM)
    	{
    		printf("Too much input data!\n");
    		return (-1);
    	}
    
    	printf("Enter a student number (-99 to quit): ");
    	scanf("%d", &iTarget);
    	while (iTarget != SENTINEL)
    	{
    		iPosition = searchArray (iId, iNum, iTarget);
    		if (iPosition == -1)
    		{
    			printf ("Not in Array!\n");
    			return(-1);
    		}
    
    		printf("Student number: %d\n", iId[iPosition]);
    		printf("Mark:           %d%%\n\n", iScore[iPosition]);
    		printf("Enter a student number (or -99 to quit): ");
    		scanf("%d", &iTarget);
    	}
    
    
    
    	return (0);
    }
    
    
    
    
    /*****FUNCTIONS*****/
    
    
    
    
    /*Function to input the data from the file into the arrays and print the data*/
    int getData(int iId[], int iScore[])
    {
        int iStatus, iNum;
    	FILE *inp;
    	
    	inp = fopen("C:/Documents and Settings/Administrator/Desktop/scores.txt", "r");
    	
    	if (inp == NULL)
    	{
    		printf("Unable to open file!\n");
    		return (-1);
    	}
    		
    	iNum = 0;
    	iStatus = fscanf(inp, "%d %d", &iId[0], &iScore[0]);
    	while (iStatus != EOF)
    	{
    		iNum++;
    		iStatus = fscanf(inp, "%d %d", &iId[iNum], &iScore[iNum]);
    	}
    	
            fclose(inp); /*close the file*/
            return (iNum); /*return number of ints read*/
    }
    
    
    
    
    
    /*Function to search array for student #*/
    int searchArray (const int iId[], int iNum, int iTarget)
    {
    	int iFound, iPosition;
    	
    	/*Assume target has not been found*/
    	iFound = 0;
    	/*Loop until either target is found or we are at end of data*/
    	iPosition = 0;
    	while (iFound == 0 && iPosition < iNum)
    	{
    		if (iId [iPosition] == iTarget)
    		{
    			iFound = 1;
    		}
    		else
    		{
    			iPosition++;
    		}
    	}
    	if (iFound == 0)
    	{
    		return (-1);
    	}
    	else
    	{
    		return (iPosition);
    	}
    
    }

  9. #9
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    but it will not run.
    What does the program not do that you want it to do?

    Code:
    	iStatus = fscanf(inp, "%d %d", &iId[0], &iScore[0]);
    	while (iStatus != EOF)
    	{
    		iNum++;
    		iStatus = fscanf(inp, "%d %d", &iId[iNum], &iScore[iNum]);
    	}
    The loop above is not right. see the loop in my previous post. The fscanf() returns the number of fields that were assigned, 0 if no fields or EOF (normally -1) on error. So just testing for 2, in this case because fscanf() is supposed to assign two values.
    Last edited by Ancient Dragon; 11-03-2005 at 12:52 PM.

  10. #10
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    It won't do ***anything*** at all....It starts up, but I receive a Windows error message and the command promp shuts down.

  11. #11
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    probably because the value of iNum in main() was never set
    Code:
    	iNum = getData(iId, iScore);

  12. #12
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    I had fixed that, but even then, It still refuses to work.

  13. #13
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    your program works ok for me. Check the data file. It should look something on the order of this, but I just put several jumk values in it. If the file contains more than MAXIMUM number of rows then your program will crash because it does not make any sanity checks for array overflows.
    Code:
    10 15
    20 25
    21 22
    1 2
    3 4
    5 6
    Code:
    	while (iStatus == 2 && iNum < MAXIMUM)

  14. #14
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    You had said that this loop of mine was not right:
    Code:
    	iStatus = fscanf(inp, "%d %d", &iId[0], &iScore[0]);
    	while (iStatus != EOF)
    	{
    		iNum++;
    		iStatus = fscanf(inp, "%d %d", &iId[iNum], &iScore[iNum]);
    	}
    But it worked perfectly when I wrote the whole program in main. Why won't it work for me now?

  15. #15
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    because fscanf() does not return EOF when an error is encountered. For example suppose the file looked like this
    Code:
    10 15
    20 abc
    21 22
    fscanf() will return 1 on line 2 because it could only set one integer, and it will return 0 on every other iteration of the loop because end-of-file is never reached. fscanf() just keeps trying to convert those alpha characters to integers, and never moves the file pointer from the 2nd line. But your program will ignore that little oversight
    Last edited by Ancient Dragon; 11-03-2005 at 01:28 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. arrays, functions, HELP
    By beginner1 in forum C Programming
    Replies: 4
    Last Post: 05-20-2009, 03:29 PM
  2. Manipulating Character arrays in functions.
    By kbro3 in forum C++ Programming
    Replies: 11
    Last Post: 08-16-2008, 02:24 AM
  3. functions using arrays
    By trprince in forum C Programming
    Replies: 30
    Last Post: 11-17-2007, 06:10 PM
  4. Arrays and Functions
    By KunoNoOni in forum Game Programming
    Replies: 12
    Last Post: 10-04-2005, 09:41 PM
  5. Arrays out-of-bounds in functions only?
    By KneeLess in forum C Programming
    Replies: 5
    Last Post: 11-03-2004, 06:46 PM