CSCI 2132 Final Exam Solutions

Similar documents
Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

CSCI 2132 Final Exam Solutions

25.2 Opening and Closing a File

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

Midterm 1 1 /8 2 /9 3 /9 4 /12 5 /10. Faculty of Computer Science. Term: Fall 2018 (Sep4-Dec4) Student ID Information. Grade Table Question Score

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

Student Number: Computer Science 211b Final Examination. 28 April hours

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI 2132 Software Development Lecture 35: Dynamically Allocated Arrays, Course Review

THE UNIVERSITY OF WESTERN ONTARIO. COMPUTER SCIENCE 211a FINAL EXAMINATION 17 DECEMBER HOURS

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

Dalhousie University CSCI 2132 Software Development Winter 2018 Midterm Examination II March 12 15:37-16:24

SOFTWARE Ph.D. Qualifying Exam Fall 2017

Introduction to Supercomputing

CMPT 300. Operating Systems. Brief Intro to UNIX and C

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

CSE 333 Midterm Exam July 24, Name UW ID#

CSE 333 Midterm Exam July 24, 2017 Sample Solution

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

PRINCIPLES OF OPERATING SYSTEMS

Approximately a Test II CPSC 206

Approximately a Final Exam CPSC 206

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CSCI 171 Chapter Outlines

CSE 333 Midterm Exam Sample Solution 5/10/13

MIDTERM EXAM. CS 217 October 28, Name: Precept: Honor Code: Score: Problem Score Max

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

CSE 374 Final Exam 3/15/17. Name UW ID#

Kurt Schmidt. October 30, 2018

Pointers and File Handling

CS61, Fall 2012 Section 2 Notes

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

CSE 303, Spring 2009 Final Exam Wednesday, June 10, 2009

Midterm Exam 2 Solutions C Programming Dr. Beeson, Spring 2009

CSE 124 Discussion (10/3) C/C++ Basics

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

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C mini reference. 5 Binary numbers 12

Software Development With Emacs: The Edit-Compile-Debug Cycle

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

ECE264 Spring 2014 Exam 2, March 11, 2014

CSC209H1S Day Midterm Solutions Winter 2010

BİL200 TUTORIAL-EXERCISES Objective:

Process Management! Goals of this Lecture!

Quiz 0 Review Session. October 13th, 2014

CSE 374 Midterm Exam 2/6/17 Sample Solution. Question 1. (12 points, 4 each) Suppose we have the following files and directories:

Arrays and Pointers (part 2) Be extra careful with pointers!

Exercise 1: Basic Tools

ESC101N: Fundamentals of Computing End-sem st semester

CS240: Programming in C

CSE 374 Final Exam 3/15/17 Sample Solution. Question 1. (8 points) Suppose we have the following two statements in a C program:

FALL 2017 CSCI 304 LAB1 (Due on Sep-19, 11:59:59pm)

High Performance Programming Programming in C part 1

PROGRAMMAZIONE I A.A. 2017/2018

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

CSE 333 Midterm Exam 5/10/13

CSSE 332 Standard Library, Storage classes, and Make

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

Programming in C week 1 meeting Tiina Niklander

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Beyond this course. Machine code. Readings: CP:AMA 2.1, 15.4

CSE 333 Midterm Exam 2/14/14

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

ECE551 Midterm Version 1

Arrays and Pointers (part 2) Be extra careful with pointers!

The University of Nottingham

Programming in C First meeting Tiina Niklander

CS 610: Intermediate Programming: C/C++ Making Programs General An Introduction to Linked Lists

Tutorial 1 C Tutorial: Pointers, Strings, Exec

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

York University Faculty Science and Engineering Fall 2008

CS-220 Spring 2018 Test 1 Version A Feb. 28, Name:

Programming in C First meeting

CS 2505 Computer Organization I Test 1. Do not start the test until instructed to do so! Solution. printed

8. Characters, Strings and Files

Creating a Shell or Command Interperter Program CSCI411 Lab

CS 241 Data Organization Pointers and Arrays

Warm-up sheet: Programming in C

CSE 333 Midterm Exam 7/29/13

15213 Recitation Section C

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

Exercise Session 2 Simon Gerber

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

C & Data Structures syllabus

Today s Learning Objectives

Multiple Choice Questions ( 1 mark)

Dalhousie University CSCI 2132 Software Development Winter 2018 Lab 8, March 22

Programs in memory. The layout of memory is roughly:

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

[6 marks] All parts of this question assume the following C statement. Parts (b) through (e) assume a variable called ptrs.

C programming basics T3-1 -

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

CSE 303, Winter 2007, Final Examination 15 March Please do not turn the page until everyone is ready.

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

Fundamental of Programming (C)

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

CSE 303, Winter 2007, Final Examination 15 March Please do not turn the page until everyone is ready.

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Transcription:

Faculty of Computer Science 1 CSCI 2132 Final Exam Solutions Term: Fall 2018 (Sep4-Dec4) 1. (12 points) True-false questions. 2 points each. No justification necessary, but it may be helpful if the question seems ambiguous. a) (2 points) In the UNIX file model, a file is a stream of bytes. True. b) (2 points) Symbolic links and pipes are types of files in Unix. True. (Symbolic links and pipes are types of files in Unix. The seven types of files in Unix are: 1. regular files, 2. directory files, 3. buffered special files, 4. unbuffered special files, 5. symbolic links, 6. pipes, and 7. sockets.) c) (2 points) In the C programming language, the following two pairs of scanf format strings are equivalent: "%c,%c" "%c,%c" False. d) (2 points) In the C programming language, the following two pairs of scanf format strings are equivalent: "%d,%d" "%d,%d" False. e) (2 points) If there is a text file named log.txt in the current working directory, the command date >> log.txt will append the output of the date command to the end of log.txt. True. f) (2 points) In a shell script, whenever we used the command exit to terminate the script, we are always required to provide an exit code explicitly as the argument of the exit command. False

CSCI 2132, Final Exam Solutions 2 2. (12 points) Multiple-choice. Circle the single best answer. a) (3 points) Which of the following statements regarding streams and files in the C programming language is INCORRECT? A. In C, a stream is any source of input or any destination of output; B. The following statement will output out of memory followed by a newline character to the standard error channel: fprintf(stdout, "out of memory\n"); C. The fopen function returns NULL when it fails to open a file; D. The notion of lines does NOT apply to binary files. B. b) (3 points) If c is a variable of type char, which one of the following statements is illegal? A. i += c; /* i has type int */ B. c = 2 * c - 1; C. printf(c); D. putchar(c); C. c) (3 points) Suppose that the following declarations are in effect: int a[] = {17, 211, 10, -5, 14, 19; int *p = &a[3]; What is the value of *(p+2)? A. 10 B. -5 C. 14 D. 19 D. d) (3 points) A file names contains people names. Each line contains a first name and a last name of a person (e.g. John Smith), and the file is not sorted. Our task is to list only first names, sorted alphabetically, and no name should be repeated in more than one line. Which one of the following four command will complete this task correctly? A. cut -d " " -f 1 < names uniq sort B. cat names cut -d " " -f 1 sort uniq C. sort uniq cut -d " " -f 1 names D. sort < names uniq cut -d " " -f 1 B.

CSCI 2132, Final Exam Solutions 3 3. (6 points) Program Output. What is the output of the following program? You can justify your answer, but it is not required. int a[10] = {1, i; int *p = &a[4]; int *q = p+1; for (i=1; i<10; i++) a[i] += a[i-1]+2; *(p++) = *(q++); q++; *(p++) = *(q++); printf(" %d %d %d\n", *a + *q - *p, q-p, *q-*p); for (i = 4; i < 8; i++) printf(" %d", a[i]); Short answer: 5 2 4 11 15 13 15 [Marking scheme: 3 points each row] After the first three lines, which start with int, we have: 0 1 2 3 4 5 6 7 8 9 a: 1 0 0 0 0 0 0 0 0 0 p q After the first for-loop: 0 1 2 3 4 5 6 7 8 9 a: 1 3 5 7 9 11 13 15 17 19 p q After the next line with pointer arithmetic: 0 1 2 3 4 5 6 7 8 9 a: 1 3 5 7 11 15 13 15 17 19 p q Now, the first printf command will produce: 5 2 4 because: 1 + 17 13 = 5, 8 6 = 2, and 17 13 = 4. The next for-loop prints the value of array a from 4 to 7, which are: (i=4)11 (i=5)15 (i=6)13 (i=7)15

CSCI 2132, Final Exam Solutions 4 4. (6 points) Explain briefly. Show the content of the standard main parameters: argc and argv when we call the compiled program in the following way:./a.out apple pine orange cherry If there are any pointers or strings, show them graphically. The parameter argc contains the total number of arguments in the command line, including the program name, so its value is: argc: 5 The parameter argv is an array of pointers to the arguments, and its value can be shown graphically as follows: argv:./a.out apple pine \0 \0 orange cherry \0 \0 \0 No marks are lost if the final NULL pointer in argv is not shown. Marking scheme: 2pt for argc, 4pt for argv.

CSCI 2132, Final Exam Solutions 5 5. (7 points) Program Output. What is the output of the following program? #include <stdio.h> #include <string.h> int main() { char s[90] = "test"; char *p = "program"; printf("%d %d\n", strlen(s), strlen(p+2)); puts(strcat(s, p)); printf("%d\n", strlen(s)); return 0; 4 5 testprogram 11

CSCI 2132, Final Exam Solutions 6 6. (9 points) Single command line. For each of the following questions, write a single Unix command line to perform the task required. a) (3 points) Print a list of files in the directory /usr/bin whose names end with the English word make. The file named make is considered one of these files. ls /usr/bin/*make b) (3 points) Print out the number of six-character words in the Linux dictionary file /usr/share/dict/linux.words starting with a or c and ending with h. Recall that this dictionary file contains one English word per line. grep ^[ac]...h$ /usr/share/dict/linux.words wc -l c) (3 points) Print out a list of regular files in the directory /usr/bin whose file owner has read permission but does not have execute permission. ls -l /usr/bin grep "^-r.-"

CSCI 2132, Final Exam Solutions 7 7. (8 points) Give concise answers. a) (4 points) Write down the full names (NOT abbreviations) of four gdb commands, i.e. those commands that you can enter in the gdb console. For each command you put down, write a short sentence to explain what this command is for. You are not required to explain the usage such as parameters or options of these commands; the explanation that you write just have to be sufficient to show that you know what these commands do. E.g., next -- executes next line of code step -- executes the next line of code, but steps into function when a function call is executed continue -- continues execution until the next breakpoint or program termination breakpoint line -- to set a breakpoint b) (4 points) Suppose that you are working in a directory that is a working copy of a directory in SVN. You created a new file, named file.c in your directory. Which command lines are required to save this file in the SVN repository? svn add file.c svn commit -m file.c added

CSCI 2132, Final Exam Solutions 8 8. (8 points) Give concise answers. a) (4 points) Briefly explain the keyword static when used with a variable inside a function and outside a function. When the keyword static is used inside a function, the declared variable is a static variable that keeps its value from function call to function call, but it is visible only inside the function. When the keyword static is used outside of a function, the declared variable is static but visible only inside the current source code file, and not from other source code files. b) (4 points) The following is supposed to be an implementation of the strcpy function in the standard C library, but there are two errors. Find out these errors, explain why they are incorrect, and fix these errors by modifying the code printed below. char* strcpy(char *s1, const char *s2) { int i = 0; while (s2[i]!= \0 ) { s1[i] = s2[i]; i++; return s2; Error 1: s1 will not be NULL-terminated after the function call. This is an error as C strings are terminated with NULL. Add s1[i] = \0 ; after the loop. Error 2: The function returns s2 instead of s1. Change return s2; to return s1;

CSCI 2132, Final Exam Solutions 9 9. (10 points) Large program organization. (10 points) Assume that you have a project with the following files: main.c containing the main function, llist.c containing a linked list implementation, and llist.h a header file containing all function prototypes. The file llist.h is included in the two source files main.c and llist.c. a) (4 points) What code you need to write in llist.h to protect it against double-inclusion? #ifndef LLIST_H #define LLIST_H /* some content... * #endif b) (6 points) Write a makefile to compile the program into the executable named llist when we run the command make or make all. The make should do separate compilation of files main.c and llist.c. # makefile for the program llist.phony: all all: llist llist: llist.o main.o gcc -o llist llist.o main.o llist.o: llist.c llist.h gcc -c llist.c main.o: main.c llist.h gcc -c main.c 2pt (must be first target) 2pt 1pt 1pt clean: rm rpn rpn.o stack.o Note: Including the special.phony target, and the clean target are not mandatory for full marks.

CSCI 2132, Final Exam Solutions 10 10. (10 points) Give brief answer. a) (5 points) Briefly describe what the malloc function does and its time efficiency. The malloc function reserves a block of memory on the heap, of the required size and returns a pointer to it. (Optional: The function also records the size of the block in a memory location just before the block.) The function searches for a block of the appropriate size by traversing a linked list of free blocks. If it does not find a block of the appropriate size, it uses a system call to request more memory from the operating system kernel, and adds this memory to the heap. If it does not succeed to get appropriate additional memory, it returns NULL. The malloc function is typically fast, but it may take some time if the list of the free blocks is very long, and if it needs to execute the system call. Marking scheme: 1pt - reserves a block of memory 1pt - size given as parameter 1pt - returns a pointer 1pt - returns NULL if not successful 1pt - traverses a linked list of blocks, so it may take some time - may need to call system call for more memory (if this is mentioned it is a bonus 1pt, but total cannot go over 5pt) b) (5 points) Briefly describe the mergesort algorithm, its advantages and disadvantages, and discuss running time. If you want to use code, use pseudo code. The mergesort algorithm can be applied to sort arrays, but also linked lists. The algorithm works by dividing the array into two halfs, recursivelly sorting each half by invoking itself, and then merging the sorted half into the final array. The base recursion case is when the array has only one element. The merge operation works by reading through two sorted arrays from the start in parallel, comparing the two next elements in the arrays, and copying and proceeding with the element that comes first in the sorting order. The algorithm is an efficient algorithm since it has O(n log(n)) running time. An advantage is that it works very well with linked lists (and large files). It is also a stable sort algorithm. A disadvantage is that it may not be as efficient in practice on arrays as the quicksort. Marking scheme: 2pt - for showing understanding of merge sort (2 operations: recursive split, and merge 1pt for a valid advantage 1pt for a valid disadvantage 1pt for correct running time

CSCI 2132, Final Exam Solutions 11 11. (10 points) Code snippets (10 points) Write a C program that reads a sequence of integers, one integer per line, from the standard input. For each input integer n, such that n 1, the program must print the sum of all positive integers k such that 1 k n. The input will contain one integer less than 1, and the program must terminate once it reads this integer. #include <stdio.h> int main() { int n, k, sum; while (1==scanf("%d", &n) && n>=1) { sum = 0; for (k=1; k<=n; k++) sum += k; printf("%d\n", sum); return 0;

CSCI 2132, Final Exam Solutions 12 12. (9 points) Shell scripting a) (3 points) Briefly explain how shell interprets double parentheses in a command, such as: (( some expression )) The double parantheses in bash shell are interpreted as arithmetic expressions, or as an arithmetic for-loop if preceeded with the command for. b) (6 points) Briefly explain the lines (1), (2) and (3) in the shell script below: if [! -d $1 ]; then echo Error (1) exit 1 fi if [ -f $1/testfile.txt ]; then (2) if [! -e tmp/testfile.txt ]; then (3) cp $1/testfile.txt tmp/testfile.txt fi fi The line (1) is an echo command used to echo an Error message as a result of a previous test. Additional explanation: If the first argument given to the script ($1) is not a directory, the error will be printed and the script will exit. The line (2) tests whether there exists a regular file with the name $1/testfile.txt. The line (3) tests whether there does not exist a file with the name tmp/testfile.txt. The lines (2) and (3) ensure that it is possible to copy the file $1/testfile.txt to the file tmp/testfile.txt, without overwriting an existing file.

CSCI 2132, Final Exam Solutions 13 13. (8 points) File operations in C (8 points) Consider the following two choices for opening a file: FILE *fp = fopen("foo", "ab+"); /* choice A */ FILE *fp = fopen("foo", "a+"); /* choice B */ and the following two choices for writing the double variable x to the file: fprintf(fp, "%lf\n", x); /* choice C */ fwrite(&x, sizeof(double), 1, fp); /* choice D */ a) Which choices for opening the file and writing to the file are appropriate to be used together? Why? b) Give one advantage for each choice of writing x to the file. a) The appropriate choices are: A-D and B-C, because in A-D we assume that the file is binary, and in B-C we assume that the file is a textual file. [4pt = 2pt for choices, 2pt for explanation] b) An advantage of binary file is that we save on disk space (memory) because the representation is more compact. (Another advantage is that we do not loose on precision.) [2pt] An advantage of textual file is that the representation is more clear and easy to inspect externally. (Another advantage is that the representation is more portable because it does not depend on an internal memory representation of floating-point numbers.) [2pt]

CSCI 2132, Final Exam Solutions 14 14. (32 points) Write a C program. (32 points) Assume that you are working on a program to process product prices. The data will be stored in a linked list where the structure of a node is given in C as follows: struct node { char prod[50]; /* prod is product name */ double price; /* price is product price */ struct node *next; /* next is pointer to next node */ ; (a) (4 marks) Write a C function printprod that takes a pointer to the above node structure and prints a line with the following: the product name, a comma (,), the product price, another comma, and a newline character to the standard output. An output example is: office desk, 356.78, The function prototype must be: void printprod(struct node *n); void printprod(struct node *n) { printf("%s, %lf,\n", n->prod, n->price);

CSCI 2132, Final Exam Solutions 15 (b) (10 marks) Write the C function readprod which allocates a node structure, and fills it with a product name, price, and sets member next to NULL. The product name and price are read from the standard input. The input format is as follows: orange juice, 5.95,... so, the product name consists of some characters that are not comma, followed by a comma, followed by product price, followed by comma, and some other optional characters in a line. You can assume that product name is not longer than 49, and the function should also read all characters to the end of line but not store them anywhere. You do not need to do much error checking except that if you cannot read input in required format the function should return NULL. The function returns a pointer to the structure created like this. The function prototype is: struct node* readprod(); struct node* readprod() { struct node *r = malloc( sizeof(struct node) ); /* 2pt */ if (2!= scanf("%[^,],%lf", &(r->prod[0]), &(r->price))) { /* 4pt */ free(r); return NULL; /* 1pt */ r->next = NULL; /* 1pt */ scanf("%*[^\n]\n"); /* 2pt */ return r;

CSCI 2132, Final Exam Solutions 16 (c) (10 marks) Write the C function insert which inserts a node into a linked list. You can assume that list has products sorted by price from high to low, and after inserting the node, the list should remain sorted. The first argument head is the pointer to the first element of the list, or NULL if the list is empty. The second argument newnode is the new node to be inserted. The function returns the new head of the list. The function prototype is: struct node* insert(struct node *head, struct node *newnode); struct node* insert(struct node *head, struct node *newnode) { struct node *prev, *p; if (head==null) return newnode; /* 1pt */ if (newnode->price > head->price) { /* 2pt */ newnode->next = head; return newnode; prev = head; p = head->next; /* 1pt */ while (p!= NULL && p->price > newnode->price) { /* 3pt */ prev = prev->next; p = p->next; prev->next = newnode; newnode->next = p; /* 2pt */ return head; /* 1pt */

CSCI 2132, Final Exam Solutions 17 (d) (8 marks) Write a C program that reads a sequence of products and prints them out sorted by their price from high to low. The program must read the the products using the function readprod defined in (b), insert them into a linked list using the function insert defined in (c). The products must be printed using the function printprod defined in (a). Write a complete program with includes and the function main, but you can assume that the functions printprod, readprod, and insert are already defined and their prototypes included, and struct node already defined. #include <stdio.h> /* 1pt */ int main() { struct node *head=null, *h; /* 1pt */ while (NULL!= (h = readprod())) /* 2pt */ head = insert(head, h); /* 1pt */ for (h = head; h!=null; h = h->next) /* 2pt */ printprod(h); /* 1pt */ return 0; A tentative marking scheme is included on the side. An include such as stdio or stdlib is required for NULL to be defined.