Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Best way to do this

Name: Alex 2011-11-24 18:12

Hey /g/. I'm doing an assignment and it asks me to read in a bunch of integers from a text file into an array (marks for assignments). I have an array[10][4], 10 students with 4 grades each.

What I want to do is check the value of these grades, and if they're say <=40, then do something, if they're >70, do something. I need to count up the number of marks in each bracket. I could easily do this using for loops in the main function, but it seems very messy and we're marked on the way we implement the program rather than simply solving the problem.

I tried to use the array as a parameter to a function, and then use the function to check the values, but I couldn't get this to work. Could I use pointers to do this? Jus tell me the best way to do it /g/, I can try to implement it myself. The language is C, by the way.

Name: Anonymous 2011-11-24 18:31

#include <stdio.h>

int main(int argc, char** argv)
{
    FILE* input = NULL;
    char grades[10][4];
    int i, j;
    int low = 0, medium = 0, high = 0;

    /* print usage if no input argument */
    if(argc < 2){
        printf("usage: %s input.txt\n", argv[0]);
        return 0;
    }

    /* open input file */
    input = fopen(argv[1], "r");
    if(!input){
        printf("Could not load text file\n");
        return 0;
    }

    /* read in the grades */
    for(i = 0; i < 10; i++)
        for(j = 0; j < 4; j++)
            fscanf(input, "%c", &grades[i][j]);

    /* look at the "brackets" */
    for(i = 0; i < 10; i++)
        for(j = 0; j < 4; j++)
            if(grades[i][j] <= 40)        ++low;
            else if(grades[i][j] > 70)    ++high;
            else                ++medium;

    /* show results */
    printf("There were %d low grades, %d average grades, and %d high grades\n",
        low, medium, high);

    /* close input file */
    fclose(input);

    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List