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.
That's amazing, and it's the best way to go about it? The lecturer and his preceptors are awkward bastards and will mark you down for little things, I don't want to give them excuses.
I could already do this, but I thought that there might have been a better way to go about it, using pointers or something like that. If this is the best way then surely they'll be happy with it.
Name:
Anonymous2011-11-24 18:40
>>9
I think >>8 fixes the segfault. And I guess OP can look at the code above as an example only, as I am now claiming copyright on it.
Name:
Anonymous2011-11-24 18:41
>>11
I think indeed the best way is the simplest way.
You can make this code into a 2D array easily. Just divide the memory pointed to by int *store; by the number of students and traverse it by that much at a time.
Arrays and pointers are the same, as >>17-san says.
for (j = 0; j < 10; ++j){
for (k = 0; k < 4; ++k){
fprintf(stdout, "%d\n", (&store[j])[k]);
}
}
fclose(grades);
free(store);
return 0;
}
Store is treated as a 2D array, you can also cast it to one.
Name:
Anonymous2011-11-24 19:55
They will probably mark you down if you are too verbose. Lecturers hate reading through page after page of inefficient newb code.
Keep it short and sweet, with a twang:
#include <stdio.h>
void main(int argc, char** argv) {
char i=0, j=0, grades[10][4];int ranks[3]={};
for (FILE* f = fopen(argv[1],"r"); fscanf(f,"%hhd",&grades[i][j])==1 && ++ranks[(int)((3-((100-grades[i][j])/30))*0.9)]||fclose(f)&&0;j=(j+1)&3,i+=!j);
printf("There were %d low grades, %d average grades, and %d high grades\n", *(struct{int a,b,c;}*)ranks);
}