Question

Locked

C PROGROMMING NEED HELP!!!

By billwhite16 ·
Hi, i need to write a c program, that reads a list of integers from a text file, and then prints these list of integers. then prints the average of the integers, the minimum value, and the maximum value! i dont know how to do this, as when you read from a file, you only have one variable, so how can they be added together, do i need a while or a for loop!
this is what i have so far, and all it does is read the list of integers, and prints them onto the screen! the program must also adapt so if i change the number of integers, then the average will change, and if i change the lowest or highest integer, then the min and max output will change. i think i need an if statement that reads the current value to check if it is lower than the previous value...ahhh!! please help!!


#include <stdio>

int main(){

//input from a file//
FILE *inf;

//declare variables//
float data,sum,min,max;
int ii;

//read from that file//
inf=fopen("textfile.txt","r");

//exercise safe file opening//
if (inf!=NULL){

//loop till end of file//
while (feof(inf)==0){

//read the data from the file//
fscanf(inf,"%f",&data);

//print the data//
printf("%.2f\n",data);

}

fclose(inf);

}

//print error message if file does not exist//
else {
printf("file does not exist\n");
}


return(0);

}

This conversation is currently closed to new comments.

2 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Answers

Collapse -

Two options

by Tony Hopkinson In reply to C PROGROMMING NEED HELP!! ...

One you can read it in to a list and then process that, or uick nasty and probably waht you are after.

Four varaiables to hold min,max, sum and count.
Intiialise them, biggest, smallest, 0 and 0.

Inside the the loop test the current value against min and max, add it to sum, and increment count
After the loop print out min and max and work out the average print that.

You might want to think about the impact of negatives, and for Cthulu's sake test for count = 0 before you divide by it.

HtHs

Back to Peripheral Forum
2 total posts (Page 1 of 1)  

Related Discussions

Related Forums