Download
array functions n.
Skip this Video
Loading SlideShow in 5 Seconds..
Array & Functions PowerPoint Presentation
Download Presentation
Array & Functions

Array & Functions

100 Views Download Presentation
Download Presentation

Array & Functions

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Array & Functions Reading From a File

  2. FILE Operations • FILE pointer declarations • FILE *flptr; • Open a file • flptr = fopen(“filename”, “r”); • “r” for read only, “w” for writing • Read from a file – same as scanf • fscanf(flptr, “%d%f %c”, &a, &b, &c); • Write to a file – same as printf • fprintf(flptr, “This is output %8.2f\n”, w); • Close a file • fclose(flptr);

  3. Example • Read grades from a file, find minimum, maximum, and average • fscanf returns EOF when it reaches the end of file. i=0; do { Status = fscanf(flptr, “%f”, &grd[i]); i++; } while(Status != EOF);

  4. Example - Main • #include <stdio.h> • #define CLSZ 100 • intFillArr(FILE *flp, intgr[]); • intFindMax(intgr[], intsz); • intFindMin(intgr[], intsz); • double FindAve(intgr[], intsz); • int main(void) { • FILE *flptr; • intGrd[CLSZ], SZ; • int Min, Max; • double Ave; • flptr = fopen("Grades.txt", "r"); • SZ = FillArr(flptr, Grd); • Max = FindMax(Grd, SZ); • Min = FindMin(Grd, SZ); • Ave = FindAve(Grd, SZ); • printf("The Maximum is: %3d\n", Max); • printf("The Minimum is: %3d\n", Min); • printf("The Average is: %6.2f\n", Ave); • fclose(flptr); • return(0); • }

  5. Example - Functions • intFindMin(intgr[], intsz) { • inti, min; • min = gr[0]; • for(i=1; i<sz; i++) • if(gr[i] < min) min=gr[i]; • return(min); • } • double FindAve(intgr[], intsz) { • double ave = 0.0; • inti; • for(i=0; i<sz; i++) ave+=gr[i]; • ave=ave/sz; • return(ave); • } • intFillArr(FILE *flp, intgr[]) { • int Status, i=0; • Status = fscanf(flp, "%d", &gr[i]); • while(Status != EOF) { • i++; • Status = fscanf(flp, "%d", &gr[i]); • } • return(i); • } • intFindMax(intgr[], intsz) { • inti, max; • max = gr[0]; • for(i=1; i<sz; i++) • if(gr[i] > max) max=gr[i]; • return(max); • }