MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

Similar documents
Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Ch 11. C File Processing (review)

Chapter 11 File Processing

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

C mini reference. 5 Binary numbers 12

Lecture 9: File Processing. Quazi Rahman

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)

ENG120. Misc. Topics

Lecture6 File Processing

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Chapter 12. Files (reference: Deitel s chap 11) chap8

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

ECE551 Midterm Version 1

Intermediate Programming, Spring 2017*

CSCI 171 Chapter Outlines

CSI 402 Lecture 2 Working with Files (Text and Binary)

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

C File Processing: One-Page Summary

Standard C Library Functions

System Software Experiment 1 Lecture 7

C programming basics T3-1 -

ECE551 Midterm Version 2

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

UNIT IV-2. The I/O library functions can be classified into two broad categories:

ECE264 Spring 2014 Exam 2, March 11, 2014

Standard File Pointers

C: How to Program. Week /June/18

Chapter 8 - Characters and Strings

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

Introduction to Computer Programming Lecture 18 Binary Files

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Computer programming

C PROGRAMMING. Characters and Strings File Processing Exercise

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

STRUCTURES & FILE IO

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Signature: ECE 551 Midterm Exam

Input/Output and the Operating Systems

Fundamentals of Programming. Lecture 15: C File Processing

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

PROGRAMMAZIONE I A.A. 2017/2018

CS 261 Fall Mike Lam, Professor. Structs and I/O

Introduction to Data Structures. Systems Programming

Advanced C Programming and Introduction to Data Structures

Characters and Strings

Computer Programming Unit v

CS1003: Intro to CS, Summer 2008

File I/O. Arash Rafiey. November 7, 2017

ESC101N: Fundamentals of Computing End-sem st semester

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

System Programming. Standard Input/Output Library (Cont d)

Character Strings. String-copy Example

CSI 402 Lecture 2 (More on Files) 2 1 / 20

CS240: Programming in C

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

COP 3223 Final Review

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

EM108 Software Development for Engineers

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

C Basics And Concepts Input And Output

ECE264 Spring 2013 Exam 1, February 14, 2013

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Contents. A Review of C language. Visual C Visual C++ 6.0

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Computer System and programming in C

ECE551 Midterm Version 1

25.2 Opening and Closing a File

Algorithms & Programming. Midterm Examination # 2. Student Name: Student ID Number: Duration of examination:

Euclid s algorithm, 133

JTSK Programming in C II C-Lab II. Lecture 3 & 4

C Libraries. Bart Childs Complementary to the text(s)

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Dynamic memory allocation

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

C-Refresher: Session 10 Disk IO

Procedural Programming

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

C: How to Program. Week /May/28

Chapter 8: Character & String. In this chapter, you ll learn about;

M.CS201 Programming language

8. Characters, Strings and Files

Answer all questions. Write your answers only in the space provided. Full marks = 50

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

by Pearson Education, Inc. All Rights Reserved.

Advanced Pointer Topics

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

Do not start the test until instructed to do so!

ECE 2035 Programming HW/SW Systems Spring problems, 5 pages Exam Three 8 April Your Name (please print clearly)

A Crash Course in C. Steven Reeves

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Transcription:

FINAL EXAMINATION INTRODUCTION TO ALGORITHMS AND PROGRAMMING II 03-60-141-01 U N I V E R S I T Y O F W I N D S O R S C H O O L O F C O M P U T E R S C I E N C E Winter 2014 Last Name: First Name: Student ID: PLEASE READ CAREFULLY BEFORE YOU START 1. This is a CLOSED book test; no notes, textbooks, calculators or computer aids are allowed. 2. PRINT your name legibly and clearly with your Student ID in the space indicated above. 3. You will be asked to sign your name, once during the exam (sign-in) and once before leaving the exam room (sign-out). 4. Answer all the questions in the space provided. DO NOT REMOVE any pages or attach any papers to this test. If you need more space please request an additional exam booklet which MUST be returned with this exam paper with your name and ID clearly written on it. 5. You are not allowed to give or receive unauthorized help with your test. Any misconduct, as outlined by the Senate bylaw 31 article I, will be reported accordingly. Such misconduct includes any attempt, by any means whatsoever, to copy answers from other students, or to receive any unauthorized assistance answering any and all questions. 6. You have 3 hours to complete this test. 7. Final examination papers are not returned to students. 8. You may view your exam paper during the specified date and time to be posted by your instructor. 9. It is recommended that you document your code to clarify ambiguities or partial answers. Good Luck! MARKS: Q1 Q2 Q3 Q4 Q5 Q6 TOTAL: /20 /15 /15 /15 / 5 /30 /100 Page 1 of 16

Q1. [20 MARKS] For each part below, write a single C language statement that answers the question. A. Write a statement that opens the file master.dat for reading and assigns the returned file pointer to mfptr. Assume that the file contains only character data with variable length records. [1 mark] mfptr = fopen( master.dat, r ) ; B. Write a statement that reads a record from a file to which cfptr points. Assume that the record consists only of an integer Number and string Name, both stated in character form and the inputs are to be stored in variables Number (int) and Name (char *). [1 mark] fscanf( cfptr, %d%s, &Number, Name ) ; C. Convert the alphabetic character stored in the variable C (char) to an uppercase letter, storing the result in C. [1 mark] C = toupper( C ) ; D. Read an entire line of text into array of characters S, from the keyboard. You are not permitted to use either scanf or fscanf. [1 mark] fgets( S, 200, stdin ) ; // NOTE: any reasonable value >= 100 is OK gets( S ) ; // This also is fine E. Assuming that Ptr is a pointer to a character, assign to Ptr the location of the first occurrence of a character C in string S. [2 marks] Ptr = strchr( S, C ) ; for( Ptr=S ; C!= *Ptr && *Ptr!= \0 ; Ptr++ ) ; // This is also OK for 1 mark only // Note that if C is not found, Ptr ends up set to \0 Page 2 of 16

F. Assuming that both S1 and S2 are defined as string variables of appropriate length, append (or concatenate) no more than the first 10 characters from the string in S2 to the string in S1. [1 mark] strncat( S1, S2, 10 ) ; // Note: A for-loop approach might work, but is likely to be complicated. Watch for such answers and give part marks if they are on the right track. G. Assuming that both S1 and S2 are defined as string variables, compare the string in S1 with the string in S2, within a printf function, so that the result of the string comparison is outputted. [1 mark] printf( %d, strcmp( S1, S2 ) ) ; H. Assume that a float variable Number has been declared. Declare and initialize a pointer nptr to Number. [1 mark] float * nptr = &Number ; I. Define Part_t to be a synonym (i.e. user defined type) for the type struct Part. [1 mark] typedef struct Part Part_t ; J. Write a statement that opens the file DAmaster.dat for both reading and writing and assigns the returned file pointer to mfptr. Assume that the file contains machine readable (i.e. binary) data with fixed length records. [1 mark] mfptr = fopen( DAmaster.dat, rb+ ) ; Page 3 of 16

K. Assuming that the direct access file DAmaster.dat has been opened for reading and writing and file pointer value has been assigned to mfptr. Write a statement that outputs the structure Part to DAmaster.dat. [2 marks] fwrite( &Part, sizeof( Part ), 1, mfptr ) ; L. Assume the declarations: double A[10][20], *Aptr = &A[0][0]; Write a single for loop statement that stores the value 9.9 into the first column location in each row within the array A (i.e. A[0][k]), using only the pointer Aptr provided as stated. [2 marks] for( ; (Aptr-&A[0][0])/(20*sizeof double); Aptr += 20*sizeof double ) *Aptr = 9.9 ; // Watch for alternative, correct solutions. M. Assume the declarations: char A, B; and further assume that the actual 8-bit values stored in A=01011010, B= 11111111. Write a single statement that operates on both A and B to produce the result 10100101, which is stored in A. [2 marks] A = A ^ B ; N. Assume that Aptr has been declared and initialized as a pointer to a dynamically allocated structure. Write a single statement that deallocates the structure pointed to by Aptr. [1 mark] free( Aptr ) ; O. Assuming the definitions: int C; char S[256]; write a single statement that counts the number of records inputted from stdin, storing the count result in C and assuming that no input record contains more than 255 characters. [2 marks] for( C=0 ; feof( stdin )!= EOF ; C++ ) ; // Watch for correct alternative solutions using gets() or fgets() Page 4 of 16

Q2. [15 MARKS] Part A. [8 marks] Consider the definition of the string processing function strspn(), whose prototype is defined as: size_t strspn( const char * S1, const char * S2 ); Definition: String S1 is searched, and returns the length of the initial substring segment in S1 that contains only characters found in S2. As an example: printf("%d", strspn("the-cat-and-the-rat", "-echt") ); produces output 5. Write a complete C function definition of strspn() that follows the definition above. You may not use any C library functions! size_t strspn( const char * S1, const char * S2 ) { int N = 0 ; char * p1 = S1, * p2 ; // Decl. 2 mks while( *p1!= \0 ) { for( p2=s2 ; *p2!= \0 ; p2++ ) if( *p1 == *p2 ) { N++ ; break ; // Break from for-loop if( *p1!= *p2 ) break ; // Break from while-loop p1++ ; // Log. 5 mks return N ; // Ret. 1 mks // I expect alternative solution strategies. Be sure to trace the logic to ensure correctness, or not. Do not over-penalize minor syntactic errors. If it is clear what the student is trying to do, but their syntax is consistently wrong, you may consider partial marks. Page 5 of 16

Question 2 (Continued) Part B. [7 marks] Consider the definition of the string processing function strpbrk(), whose prototype is defined as: char * strpbrk( const char * S1, const char * S2 ); Definition: Locates the first occurrence in S1 of any character found in S2, and returns a pointer to that position in S1. Otherwise a NULL value is returned. As an example: printf("%s", strpbrk(("the quick crazy cat", "aktz") ); produces the output string "k crazy cat". Write a complete C function definition of strpbrk() that follows the definition above. You may not use any C library functions! char * strpbrk( const char * S1, const char * S2 ) { char * p1 = S1, * p2 ; while( *p1!= \0 ) { for( p2=s2 ; *p2!= \0 ; p2++ ) if( *p1 == *p2 ) { return p1 ; p1++ ; // Decl. 2 mks // Log. 4 mks return NULL ; // Ret. 1 mks // I expect alternative solution strategies. Be sure to trace the logic to ensure correctness, or not. Do not over-penalize minor syntactic errors. If it is clear what the student is trying to do, but their syntax is consistently wrong, you may consider partial marks. Page 6 of 16

Q3. [15 MARKS] Write and document a C function named substrcnt that takes two parameters of type character pointer, str1 and str2. The function substrcnt counts the number of occurrences of the (sub)string str2 in the string str1 and returns the count, assuming that each parameter is a valid, initialized string. [You may use any library function(s) as needed]. Example: Given: str1 = "The cat and the rat"; and str2 = "at"; printf("%d", substrcnt(str1, str2)); // will print 2. printf("%d", substrcnt("aardvark", "a")); // will print 3. int substrcnt( const char * str1, const char * str2 ) { // Prot. 3 mks char * p1 = str1 ; // Decl. 2 mks int Cnt = 0 ; while( *p1!= \0 && p1!= NULL ) { if( p1=strstr( p1, str2 )!= NULL ) { Cnt++ ; // If str2 is found, count it p1++ ; // and continue searching else return Cnt ; // If str2 not found, return return Cnt ; // Log. 8 mks // Ret. 1 mks // Ret. 1 mks // I expect alternative solution strategies. Be sure to trace the logic to ensure correctness, or not. Note that my approach uses two return statements to account for an empty str1. My solution uses strstr() and this makes it quite straightforward. If students develop their own functions, or code substring search into their solution, expect the code to be considerably more complicated, requiring careful tracing of the logic. Do not over-penalize minor syntactic errors. If it is clear what the student is trying to do, but their syntax is consistently wrong, you may consider partial marks. Page 7 of 16

Q4. [15 MARKS] Write a complete C program that satisfies the following requirements: a. Defines a 2-dimensional array of integers, A, with number of rows and columns defined by MAXROW and MAXCOL respectively. These can be defined using any positive numbers greater than 50. b. Populates A with random integer values. c. Sorts all the values in A so that after the sorting is finished, the elements of A are arranged with the smallest integer in A[0][0] and the values increase across each row and continue to increase through all the rows. d. Outputs the array values from smallest to largest in each row, and for all rows in the array. e. When finished, exit the program. As an example, consider the case below showing A before and after the sorting for a 3x3 array. Before After 5 3 7 1 2 3 A = 1 9 4 4 5 6 8 2 6 7 8 9 // Solution on next page. Page 8 of 16

#include <stdio.h> // #includes and #defines #include <stdlib.h> // 3 marks #define MAXROW 75 #define MAXCOL 100 int main( ) { int A[ MAXROW ][ MAXCOL ] ; int j, k, L, Temp ; int * Ptr ; // Decl. 2 mks for( j=0; j<maxrow ; j++ ) // Enter random values for( k=0; k<maxcol ; k++ ) // 2 mks A[j][k] = rand() ; L = MAXROW * MAXCOL ; // Sorting logic below 5 mks. for( j=0; j<l-2 ; j++ ) { // Sort values I use a pntr Ptr = &A[ MAXROW-1 ][ MAXCOL-1 ] ; // and view the 2D array as for( k=l-1; k>j ; k-- ) { // a 1D list based on the if( *Ptr < *(Ptr-1) ) { // row-major ordering in Temp = *Ptr ; // memory. *Ptr = *(Ptr-1) ; *(Ptr-1) = Temp ; Ptr-- ; for( j=0; j<maxrow ; j++ ) { // Output the sorted array for( k=0; k<maxcol ; k++ ) // with 1 row per line printf( %d, A[j][k] ) ; // 2 mks printf( \n ) ; return 0 ; // Ret. 1 mks // I expect alternative solution strategies. Be sure to trace the logic to ensure correctness, or not. Although I have used a pointer to simplify the sorting logic, students may try other approaches using array indices and the modulus operation. Check these very carefully. Do not over-penalize minor syntactic errors. If it is clear what the student is trying to do, but their syntax is consistently wrong, you may consider partial marks. Page 9 of 16

Q5. [5 Marks] Consider the following situations: A bank maintains a Random Access (also known as Direct Access or Binary) file called 'RAfile.dat' for all the account holders in their system. Records for each account holder are kept in ascending order of the account numbers. You are writing parts of a C program to access those records for updating purposes. For that, you have defined a C-structure called 'Account' (short name for struct account), to temporarily store the records of an account holder inputted from the file. Right now you are not concerned about the number and types of the members of the structure, except for the first member, which is called 'AccountNum' and has 'int' type. The file is organized so that 'AccountNum' is used as the record number. In the main() function, assume that you have declared the following variables: 1. 'pfile' a FILE pointer currently pointing to the bank's account holders' file. (File name is not important). 'pfile' has been opened with both input and output streams. 2. 'anaccount' a variable of type 'Account'. (Currently having no significant values for the members). 3. 'numacc' a variable of type 'int'. This variable currently contains the account number you want to access. Assume that the position of the read/write head is unknown. a. Write the statement(s) needed to open a file called 'RAfile.dat', locate and read the records of the account holder having the account number 'numacc' from the file into 'anaccount'. [3 marks] pfile = fopen( RAfile.dat, rb+ ) ; fseek( pfile, numacc*sizeof( Account ), SEEK_SET ) ; fread( &anaccount, sizeof( Account ), 1, pfile ) ; // 1 mk // 1 mk // 1 mk b. Write the statement(s) needed to write back the same records from 'anaccount' to the file (after possible modifications that you are not concerned with). Note that the position of the read/write head may have been changed by now. [2 marks] fseek( pfile, numacc*sizeof( Account ), SEEK_SET ) ; // 1 mk // Note: can also use the following relative seek fseek( pfile, -sizeof( Account ), SEEK_CUR ) ; // Note minus sign fwrite( &anaccount, sizeof( Account ), 1, pfile ) ; // 1 mk Page 10 of 16

Q6. [30 MARKS] Write and document a complete C program to satisfy the following requirements. Follow the structure of the following pages in answering this question. Given a sequential text file that has the following layout where each line is one record containing the following fields (separated by a single space): int id // An unique positive integer. string name // Name of the item. (Less than 20 characters, all alphabetic, first character a capital letter). float price // Unit price for the item. Example of a record in the file: 10 Apple 2.99 The file may contain any number of records up to a MAXSIZE of 5000 (five thousand) records. Each record is in a separate line. You will need to define a self-referential data structure and use a singly linked list to store input record data. You must write a complete C program to include the following features: 1. Design and declare all variables and functions as appropriate to do the processing as required for this program. (You may use a minimum set of global variables, but excessive use will be penalized). 2. Write all necessary code to: a) Read() all the records from the input file (called grocerylist.dat ) into a singly linked list. b) Display() the data of all grocery items on the screen, using the data in the linked list, according to the order of the inputs. d) Write() your results back into the file grocerylist.dat, thereby over-riding (i.e. destroying) its earlier contents. The records must be written to the file in alphabetic order by the item name, as shown in the example below. As each record is written to the file, the corresponding node of the linked list must be deallocated. When the last record has been written, the linked list must be completely empty. The functions Read(), Display() and Write() must be defined, as described later in the question. The following sample sequential text file is given to illustrate what your program must achieve: Sample contents of file grocerylist.dat before processing: 2 Tomato 2.50 4 Potato 1.75 1 Chicken 4.00 3 Beef 5.50 5 Fish 7.30 Sample contents of file grocerylist.dat after processing: 3 Beef 5.50 1 Chicken 4.00 5 Fish 7.30 4 Potato 1.75 2 Tomato 2.50 Requirements: - Your program should be able to handle a file with up to MAXSIZE records. - Write all functions necessary and explain the process of your technique (Write your algorithm clearly and document your code!) - Document and define your functions according to the instructions provided - You should assume that all the records have unique item id s. Page 11 of 16

// #includes [1 Mark] #include <stdio.h> // structure and type definitions [5 Marks] // Following are the Grocery Item structure and type definitions struct Item { int Id ; char Name[20] ; float Price ; struct Item * Next ; typedef struct Item Item_t ; // function prototypes [4 Marks] void Read( Item_t * ) ; void Display( Item_t * ) ; void Write( Item_t * ) ; Page 12 of 16

//int main ()[5 Marks] int main( ) { /*declare required variables, including pointers for linked list GList used to store input records */ Item_t * GList = NULL ; /*No menu required just invoke the function calls to satisfy the requested program sequence, then exit the program.*/ Read( GList ) ; Display( GList ) ; Write( GList ) ; return 0 ; // Code all necessary functions below [15 Marks] //Function Read [6 Marks]. Page 13 of 16

/*This function reads 'grocery' records from the file 'grocerylist.dat'. After creating a 'grocery' structure it inputs each value of a record to the structure's members. It then adds the structure to the linked list GList. The function returns after reading the entire file.*/ void Read( Item_t * Root ) { FILE * fptr ; Item_t * GLPtr, * Ptr ; fptr = fopen( grocerylist.dat, r ) ; while( feof( fptr )!= EOF ) { Ptr = (Item_t *) malloc( sizeof( Item_t ) ) ; fscanf( fptr, %d%s%f, &(Ptr->Id), Ptr->Name, &(Ptr->Price) ) ; Ptr->Next = NULL ; if( Root!= NULL ) { GLPtr->Next = Ptr ; GLPtr = Ptr ; else { Root = Ptr ; GLPtr = Ptr ; fclose( fptr ) ; return ; //Function Display [4 Marks] /*Prints the values of all the records in GList (one record in one line) as "ID NAME PRICE" format.*/ void Display( Item_t * Root ) { Item_t * Ptr = Root ; if( Root == NULL ) printf( Empty grocery list!\n ) ; // Not required while( Ptr!= NULL ) { printf( %d %s %f\n, Ptr->ID, Ptr->Name, Ptr->Price ) ; Ptr = Ptr->Next ; return ; Page 14 of 16

//Function Write [5 Marks] /*This function writes all the elements in GList into the file called 'grocerylist.dat'. The records must be written to the file in alphabetic order by the item name. After each record has been written, the node in GList must be deallocated from the list, leaving an empty list after the last record is written. */ void Write( Item_t * Root ) { FILE * fptr ; Item_t * Ptr = Root, * Ptr2, * smallptr ; fptr = fopen( grocerylist.dat, w ) ; // Destroy previous file if( Root == NULL ) { printf( No grocery list to file!\n ) ; return ; // Not required while( Root!= NULL ) { Ptr = Root ; smallptr = Root ; Ptr2 = Ptr->Next ; // Continue until no more nodes in list // Locate the node with smallest item Name while( Ptr2!= NULL ) { if( strcmp( Ptr->Name, Ptr2->Name ) > 0 ) smallptr = Ptr2 ; Ptr2 = Ptr2->Next ; // Output the record fprintf( fptr, %d %s %f\n, smallptr->id, smallptr->name, smallptr->price ) ; // Deallocate the node if( smallptr == Root ) { Root = Root->Next ; // Deletion at start of list free( smallptr ) ; else { // Deletion in rest of list for( Ptr=Root ; Ptr->Next!= smallptr ; Ptr = Ptr->Next ) ; Ptr->Next = smallptr->next ; free( smallptr ) ; fclose( fptr ) ; return ; // Do not forget to close the file Page 15 of 16

(This extra page is provided for rough work or continuation of answers) Page 16 of 16