1 / 41

CS1010: Programming Methodology comp.nus.sg/~cs1010/

CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/. Week 13: Outline. Week 12 Exercise #3: Health Screen File Processing: Introduction 2 .1 Demo #1: Sort Modules with Files 2 .2 Opening File and File Modes 2 .3 Closing File 2 .4 Other I/O Functions

pancho
Download Presentation

CS1010: Programming Methodology comp.nus.sg/~cs1010/

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/

  2. Week 13: Outline Week 12 Exercise #3: Health Screen File Processing: Introduction 2.1 Demo #1: Sort Modules with Files 2.2 Opening File and File Modes 2.3 Closing File 2.4 Other I/O Functions 2.5 Detecting End of File & Errors 2.6Demo #2: Copy File CS1010 Exam Post-CS1010 Past Years’ Questions CS1010 (AY2013/4 Semester 1) Week12 - 2

  3. 1. Week 12 Ex #3: Health Screen (1/2) • Write a program Week12_Health_Screen.c to read in a list of health screen readings • Each input line represents a reading consisting of 2 numbers: a float value indicating the health score, and an int value indicating the number of people with that score • You may assume that there are at most 50 readings • The input should end with the reading 0 0, or when 50 readings have been read. • As the readings are gathered from various clinics, there might be duplicate scores in the input. You are to determine how many unique scores there are. • A skeleton program Week12_Health_Screen.c is given. • This exercise is mounted on CodeCrunch. CS1010 (AY2013/4 Semester 1)

  4. 1. Week 12 Ex #3: Health Screen (2/2) • A sample run is shown below Enter score and frequency (end with 0 0): 5.2135 3 3.123 4 2.9 3 0.87 2 2.9 2 8.123 6 3.123 2 7.6 3 2.9 4 0.111 5 0 0 Number of unique readings = 7 • Possible extension: Which is the score that has the highest combined frequency? (Do this on your own.) CS1010 (AY2013/4 Semester 1)

  5. 2. File Processing: Introduction (1/3) • Problems on arrays usually involve a lot of data, so it is impractical to enter the data through the keyboard. • We have been using the UNIX input file redirection < to redirect data from a text file. Eg: a.out < data1 • However, that is not a C mechanism. C provides functions to handle file input/output (I/O). • We will focus on these basic file I/O functions on text file: fopen() fclose() fscanf() fprintf() CS1010 (AY2013/4 Semester 1) Week12 - 5

  6. 2. File Processing: Introduction (2/3) • In C, input/output is done based on the concept of a stream • A stream can be a file or a consumer/producer of data • Examples: screen, keyboard, hard disk, printer, network port • A stream is accessed using file pointer variable of type FILE * • The I/O functions/macros are defined in stdio.h • Two types of streams: text and binary • We will focus on text stream: • Consists of a sequence of characters organized into lines • Each line contains 0 or more characters followed by a newline character ‘\n’ • Text streams stored in files can be viewed/edited easily CS1010 (AY2013/4 Semester 1) Week12 - 6

  7. 2. File Processing: Introduction (3/3) • 3 standard streams are predefined: • stdin points to a default input stream (keyboard) • stdout points to a default output stream (screen) • stderr points to a default output stream for error messages (screen) • printf() writes output to stdout • scanf() reads input from stdin • The 3 standard streams do not need to be declared, opened, and closed • There are 2 useful constants in file processing • NULL: null pointer constant • EOF: used to represent end of file or error condition Note that null pointer NULL is not the null character ‘\0’! CS1010 (AY2013/4 Semester 1) Week12 - 7

  8. 2.1 Demo #1: Sort Modules with Files (1/4) • We modify Week12_SortModules.cto Week13_SortModules_with_Files.cto illustrate how to read a file. • The functions modified are scanModules() and printModules(). • New features introduced: • A file pointer of type FILE * • fopen() to open a text file • fscanf() to read data from the file • fprintf() to write data to a file • fclose() to close a file after use CS1010 (AY2013/4 Semester 1) Week12 - 8

  9. 2.1 Demo #1: Sort Modules with Files (2/4) Week13_SortModules_with_Files.c intscanModules(module_t mod[]) { FILE *infile; intsize,i; infile = fopen("modules.in", "r"); // open for reading fscanf(infile, "%d", &size); for (i=0; i<size; i++) fscanf(infile, "%s %d", mod[i].code, &mod[i].enrolment); fclose(infile); return size; } • Input file “modules.in” must exist for program to work. • Note that for reading data from a file, usually we do not need to provide prompt for the user, unlike in interactive input mode. CS1010 (AY2013/4 Semester 1) Week12 - 9

  10. 2.1 Demo #1: Sort Modules with Files (3/4) voidprintModules(module_t mod[], intsize) { FILE *outfile; inti; outfile = fopen("modules.out", "w"); //open for writing fprintf(outfile, "Sorted by student enrolment:\n"); for (i=0; i<size; i++) fprintf(outfile, "%s\t%3d\n", mod[i].code, mod[i].enrolment); fclose(outfile); } Week13_SortModules_with_Files.c • Output file “modules.out”, if originally exists, will be overwritten. CS1010 (AY2013/4 Semester 1) Week12 - 10

  11. 2.1 Demo #1: Sort Modules with Files (4/4) gcc –Wall Week13_SortModules_with_Files.c a.out Input file modules.in Program a.out Output file modules.out Input file must exist for program to work. CS1010 (AY2013/4 Semester 1) Week12 - 11

  12. 2.2 Opening File and File Modes (1/2) • Prototype: • FILE *fopen(const char *filename, const char *mode) • Returns NULL if error; otherwise, returns a pointer of FILE type • Possible errors: non-existent file (for input), or no permission to open the file • File mode for text files (we will focus only on “r” and “w”): CS1010 (AY2013/4 Semester 1) Week12 - 12

  13. 2.2 Opening File and File Modes (2/2) • To ensure a file is opened properly, we may add a check. Example: intscanModules(module_t mod[]) { FILE *infile; intsize,i; if ( (infile = fopen("modules.in", "r")) == NULL) { printf("Cannot open file \"modules.in\"\n"); exit(1); } . . . } • Function exit(n) terminates the program immediately, passing the value n to the operating system. Putting different values for n at different exit() statements allows us to trace where the program terminates. n is typically a positive integer (as 0 means good run). • To use the exit() function, need to include <stdlib.h>. CS1010 (AY2013/4 Semester 1) Week12 - 13

  14. 2.3 Closing File • Prototype: • intfclose(FILE *fp) • Allows a file that is no longer used to be closed • Returns EOF if error is detected; otherwise, returns 0 • It is good practice to close a file after use CS1010 (AY2013/4 Semester 1) Week12 - 14

  15. 2.4 Other I/O Functions • Formatted I/O: fprintf(), fscanf() • Uses format strings to control conversion between character and numeric data • Character I/O: fputc(), putc(), putchar(), fgetc(), getc(), getchar(), ungetc() • Reads and writes single characters • Line I/O: fputs(), puts(), fgets(), gets() • Reads and writes lines • Used mostly for text streams • Block I/O: fread(), fwrite() • Used mostly for binary streams CS1010 (AY2013/4 Semester 1) Week12 - 15

  16. 2.5 Detecting End of File & Errors • Each stream is associated with two indicators: error indicator & end-of-file (EOF) indicator • Both indicators are cleared when the stream is opened • Encountering end-of-file sets end-of-file indicator • Encountering read/write error sets error indicator • An indicator once set remains set until it is explicitly cleared by calling clearerr or some other library function • feof() returns a non-zero value if the end-of-file indicator is set; otherwise returns 0 • ferror() returns a non-zero value if the error indicator is set; otherwise returns 0 • Need to include <stdio.h> CS1010 (AY2013/4 Semester 1) Week12 - 16

  17. 2.6 Demo #2: Copy File (1/2) Week13_CopyFile.c #include <stdio.h> #include <stdlib.h> #define FNAME_LENGTH 30 voidcopyFile(char *, char *); int main(void) { charin_fname[FNAME_LENGTH + 1]; charout_fname[FNAME_LENGTH + 1]; printf("What is the input filename? "); scanf("%s", in_fname); printf("What is the output filename? "); scanf("%s", out_fname); copyFile(in_fname, out_fname); return0; } CS1010 (AY2013/4 Semester 1) Week12 - 17

  18. 2.6 Demo #2: Copy File (2/2) Week13_CopyFile.c voidcopyFile(char *sourcefile, char *destfile) { FILE *sfp, *dfp; intch; if ((sfp = fopen(sourcefile, "r")) == NULL) exit(1); // error - cannot open source file if ((dfp = fopen(destfile, "w")) == NULL) { fclose(sfp); exit(2); // error - cannot open destination file } while ((ch = fgetc(sfp)) != EOF) { fputc(ch, dfp); } fclose(sfp); fclose(dfp); } • fgetc() returns an integer. • EOF is a macro define as an int. The value is system dependent. On sunfire it is -1 CS1010 (AY2013/4 Semester 1) Week12 - 18

  19. 3. CS1010 Final Examination (1/2) • CS1010 Exam • 27 November 2013, Wednesday, 5 – 7pm • Venue: To be announced by Registrar’s Office • Format • MCQ section: 6 questions (12 marks) • Short-answer section: 5 questions (13 marks) • 4 programming questions (55 marks) • Total: 80 marks • Grading of CS1010 is not based on bell curve CS1010 (AY2013/4 Semester 1) Week13 - 19

  20. 3. CS1010 Final Examination (2/2) • Instructions • Open book • No calculators, electronic dictionaries and devices • May use 2B pencil to write codes • Advice • Read instructions carefully and follow them! • Manage your time well! • A question may consist of several parts; the parts may be independent. If you are stuck on one part, move on to the next. CS1010 (AY2013/4 Semester 1) Week13 - 20

  21. 3. How to Prepare for Exams? • Preparing for Exams: A Guide for NUS Students • http://www.cdtl.nus.edu.sg/examprep/ CS1010 (AY2013/4 Semester 1) Week13 - 21

  22. 4. Post-CS1010 (1/3) • For CS/CEG students: CS1010  CS1020  CS2010 or CS1010  CS2020 (accelerated) * • For IS/EC students: CS1010  CS1020 • CS1020 Data Structures and Algorithms I • Emphasis on algorithms and data structures • Using an object-oriented programming language Java • Textbook: Data Abstraction & Problem Solving with Java: Walls and Mirrors by Janet J. Prichard and Frank M. Carrano, 3rd edition (based on last year’s information, subject to change) • Website: http://www.comp.nus.edu.sg/~cs1020 (to be updated) CS1010 (AY2013/4 Semester 1) Week13 - 22

  23. 4. Post-CS1010 (2/3) • Topics covered (based on last year; subject to change) • Topics may not be covered in this sequence CS1010 (AY2013/4 Semester 1) Week13 - 23

  24. 4. Post-CS1010 (3/3) • CS1020 has sit-in labs (like mini-PEs) every other week • Strengthen your programming skills to prepare for CS1020 CS1010 (AY2013/4 Semester 1) Week13 - 24

  25. CS1010 (AY2013/4 Semester 1) Week13 - 25

  26. 5. Past-Years’ Questions • We will discuss some selected questions from past years’ papers. CS1010 (AY2013/4 Semester 1) Week13 - 26

  27. AY2010/11 Semester 1 Q1.3 void foo(char *fname){ FILE *fp; int c; int count = 0; if ((fp = fopen(fname, "r")) == NULL) return; while (((c = fgetc(fp)) != EOF) && (count < 3)){ if (c == '\n') count++; putchar(c); } fclose(fp); } abcde fghijklm nop qrstu... count = ? abcdefghijk... count = ? • If “dat.txt” is a text file containing 100 characters, which of the following statements is the most appropriate about the output of foo("dat.txt")? • A. The output produced by foo contains two characters. • B. The output produced by foo contains three characters. • C. The output produced by foo contains two newline characters. • D. The output produced by foo contains three newline characters. • E. None of the above. CS1010 (AY2013/4 Semester 1) Week13 - 27 

  28. AY2010/11 Semester 1 Q2(b) What is the output? #include <stdio.h> intfunctionXYZ(char *, char); int main(void){ char s[] = "abbacadaba"; printf("%d\n", functionXYZ(s, 'b')); return 0; } intfunctionXYZ(char *str, char ch){ inti=0, j=0; while (str[i]) if (str[i++] == ch) j++; return j; } s a b b a c a d a b a \0 str i j 5 1 8 2 6 9 7 3 0 10 1 3 0 4 2 CS1010 (AY2013/4 Semester 1) Week13 - 28 

  29. AY2010/11 Semester 1 Q2(c) What is the output? a #include <stdio.h> void swap(int []); int main(void){ int a[3] = {1, 2, 3}; swap(a); printf("%d %d %d\n", a[0], a[1], a[2]); swap(&a[1]); printf("%d %d %d\n", a[0], a[1], a[2]); return 0; } void swap(int x[]){ int temp = x[0]; x[0] = x[1]; x[1] = temp; } 1 2 3 CS1010 (AY2013/4 Semester 1) Week13 - 29 

  30. AY2010/11 Semester 1 Q6 (1/2) • Given R×C integer array M, find maximum number of pairs of consecutive elements within the same row or column. Assume elements are integers between 0 and 9 inclusive. • Write a function to return the maximum number of pairs of the same value in the array • intmax_pairs(int mat[][C]) 0 1 2 3 0 8 1 1 2 1 5 5 1 0 Example: 4×4 array Function returns 3 2 4 2 1 6 3 1 8 8 2 CS1010 (AY2013/4 Semester 1) Week13 - 30

  31. AY2010/11 Semester 1 Q6 (2/2) #define ROWS 100 #define COLS 100 intmax_pairs(int mat[][COLS]) { } 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 1 3 1 0 0 0 0 0 1 2 3 0 8 1 1 2 1 5 5 1 0 2 4 2 1 6 3 1 8 8 2 CS1010 (AY2013/4 Semester 1) Week13 - 31 

  32. AY2010/11 Semester 1 Q8 (1/5) int main(void) { // declare your deck of cards here // initialize the deck of cards initDeck(deck); printf("The original deck:\n"); printDeck(deck); // shuffle the deck shuffleDeck(deck); // print the deck of cards printf("\nThe shuffled deck:\n"); printDeck(deck); printf("\nPlayer's points = %d\n", computePoints(deck)); return 0; } #include <stdio.h> #include <stdlib.h> #include <time.h> #define DECK_SIZE 52 // define your card_t structure // here // function prototypes void initDeck(card_t []); void shuffleDeck(card_t []); void printDeck(card_t []); intcomputePoints(card_t []); CS1010 (AY2013/4 Semester 1) Week13 - 32 

  33. AY2010/11 Semester 1 Q8 (2/5) • printDeck function given // printDeck function given; for your reference only void printDeck(card_t deck[]) { int loop; // print the deck one card at a time for (loop = 0; loop < DECK_SIZE; loop++) { if (loop !=0 && loop % 13 == 0) printf("\n"); printf("%c%c ", deck[loop].suit, deck[loop].rank); } printf("\n"); } CS1010 (AY2013/4 Semester 1) Week13 - 33

  34. AY2010/11 Semester 1 Q8 (3/5) • Write a function initDeck to initialize the deck C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK CA D2 D3 D4 D5 D6 D7 D8 D9 DT DJ DQ DK DA H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK HA S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK SA void initDeck(card_t deck[]) { } CS1010 (AY2013/4 Semester 1) Week13 - 34 

  35. AY2010/11 Semester 1 Q8 (4/5) • Write a function shuffleDeck to shuffle the deck • Write a loop with 52 iterations. At iteration i we generate a random integer r in the range [0,51] and swap deck[r] with deck[i]. void shuffleDeck(card_t deck[]) { } CS1010 (AY2013/4 Semester 1) Week13 - 35 

  36. AY2010/11 Semester 1 Q8 (5/5) • Write a function computePoints to determine the total point of 13 cards given to a player • no-card suit: 3 pts; 1-card suit: 2 pts; 2-card suit: 1 pt 4 diamonds, 4 hearts, 3 spades  no point 2 clubs  1 point D9 C2 H9 S6 C8 D3 H2 DJ S3 D7 S8 H3 HQ intcomputePoints(card_t deck[]) { } CS1010 (AY2013/4 Semester 1) Week13 - 36 

  37. AY2012/13 Semester 1 Q4 (1/4) • A positive integer can be expressed as a product of primes • 60 = 2 × 2 ×3× 5 = 22× 31×51 • 78 = 2 ×3 × 13 = 21×31×131 • 13 = 131 • countPrimes(n) counts the number of primes to form above expression • countPrimes(60)  4; countPrimes(78)  3; countPrimes(13)  1 • Complete countPrimesRec() int countPrimes(int number) { return countPrimesRec(number, 1, 0); } • getPrime(i) is given; it returns ith smallest prime • getPrime(1)  2; getPrime(2)  3; getPrime(3)  5 CS1010 (AY2013/4 Semester 1) Week13 - 37

  38. AY2012/13 Semester 1 Q4 (2/4) This function is called with: countPrimesRec(number, 1, 0); // Pre-conditions: // // int countPrimesRec(int number, int index, int count) { int prime; if (number == 1) return count; prime = getPrime(index); if (number % prime) { } else { } } CS1010 (AY2013/4 Semester 1) Week13 - 38 

  39. AY2012/13 Semester 1 Q4 (3/4) This function is called with: countPrimesRec(number, 1, 0); // Pre-conditions: // // int countPrimesRec(int number, int index, int count) { int prime; if (number == 1) return count; prime = getPrime(index); if (number % prime) { } else { } } CS1010 (AY2013/4 Semester 1) Week13 - 39 

  40. AY2012/13 Semester 1 Q4 (4/4) int countPrimesRec(int number, int index, int count) { int prime; if (number == 1) return count; prime = getPrime(index); if (number % prime) { } else { } } getPrime(1)  2 getPrime(2)  3 getPrime(3)  5 getPrime(4)  7 getPrime(5)  11 getPrime(6)  13 • 60 = 2 × 2 × 3 × 5 = 22 × 31× 51 • 78 = 2 × 3 × 13 = 21× 31× 131 CS1010 (AY2013/4 Semester 1) Week13 - 40 

  41. End of File

More Related