CS4023 Week06 Lab Exercise

Similar documents
Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

Recitation 2/18/2012

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CS4023 Week04 Lab Exercise

Warm-up sheet: Programming in C

CSC209H Lecture 1. Dan Zingaro. January 7, 2015

Lecture 8: Structs & File I/O

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

COMP s1 Lecture 1

CS : Programming for Non-Majors, Fall 2018 Programming Project #5: Big Statistics Due by 10:20am Wednesday November

Creating a Shell or Command Interperter Program CSCI411 Lab

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

Carnegie Mellon. Cache Lab. Recitation 7: Oct 11 th, 2016

Lab 1 Introduction to UNIX and C

CpSc 1111 Lab 9 2-D Arrays

Lab 1 Introduction to UNIX and C

Welcome! COMP s1. Programming Fundamentals

Laboratory 1 Semester 1 11/12

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Cache Lab Implementation and Blocking

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

File I/O Lesson Outline

CSE 303 Midterm Exam

At the end of this module, the student should be able to:

First of all, it is a variable, just like other variables you studied

today cs3157-fall2002-sklar-lect05 1

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS Programming In C

CS143 Handout 05 Summer 2011 June 22, 2011 Programming Project 1: Lexical Analysis

Friday, September 16, Lab Notes. Command line arguments More pre-processor options Programs: Finish Program 1, begin Program 2 due next week

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

: the User (owner) for this file (your cruzid, when you do it) Position: directory flag. read Group.

Friday, February 10, Lab Notes

CSC111 Computer Science II

Introduction: The Unix shell and C programming

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

In either case, remember to delete each array that you allocate.

Computer Science & Engineering 150A Problem Solving Using Computers

Government Polytechnic Muzaffarpur.

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

CSE 361 Fall 2017 Lab Assignment L2: Defusing a Binary Bomb Assigned: Wednesday Sept. 20 Due: Wednesday Oct. 04 at 11:59 pm

CS 105, Spring 2015 Ring Buffer

CSE 351. GDB Introduction

You should see something like this, called the prompt :

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

ENCM 335 Fall 2018 Lab 6 for the Week of October 22 Complete Instructions

Week 3. This is CS50. Harvard University. Fall Cheng Gong

Homework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

CPS109 Lab 1. i. To become familiar with the Ryerson Computer Science laboratory environment.

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Writing Functions in C

CS444 1/28/05. Lab 03

Final Project: LC-3 Simulator

Welcome! COMP s1. Programming Fundamentals

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND

Lecture06: Pointers 4/1/2013

CS354 gdb Tutorial Written by Chris Feilbach

Hacking C Code - Local Machine

Lab 4. Out: Friday, February 25th, 2005

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

File I/O Lesson Outline

Lecture 03 Bits, Bytes and Data Types

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

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

C programming basics T3-1 -

Using the Debugger. Michael Jantz Dr. Prasad Kulkarni

How to program with Matlab (PART 1/3)

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

CS201 Latest Solved MCQs

CpSc 1111 Lab 4 Formatting and Flow Control

Dynamic Memory Allocation and Command-line Arguments

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

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

CSE 490c Autumn 2004 Midterm 1

COMP26120 Academic Session: Lab Exercise 2: Input/Output; Strings and Program Parameters; Error Handling

Introduction to Supercomputing

CSC209. Software Tools and Systems Programming.

COL100 Lab 2. I semester Week 2, Open the web-browser and visit the page and visit the COL100 course page.

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

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

Module 6: Array in C

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

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014)

Transcription:

CS4023 Week06 Lab Exercise Lab Objective: In this week s lab we will look at writing a program that reads a large matrix of numbers and then reports all numbers that are equal to a reference value (or within a tolerance of that value). Here s a quick summary of the tasks: ❶ Create a directory for this week s work ❷ Begin work on the findvals program. In doing this you will learn about dealing with 2-D arrays or matrices of numbers in a C program converting a string of characters that represents a number into a numerical representation reading a number from the keyboard the trick in UNIX known as file redirection how to allocate space in your program at run-time to accommodate a large array how to print out date and time in a C program and how to time how long a program runs for ❸ In the weekly directory I have provided you with an executable that will be the definitive judge in any disputes concerning formatting of output, etc. I have also left there some sample input for your program and, for the curious, a perl program that generates this sample input. ❹ When you have completed your program and when your output matches my output exactly you should hand in your program for marking. In Detail ❶ You can create this week s lab directory with mkdir ~/cs4023/labs/week06 1

Now change your working directory to this since all of our compiling, etc. will be done in this directory. ❷ The goal of this week s program is to write a program that reads a massive array of numbers and reports all numbers that are within a given tolerance of a given reference value. The reference value and the tolerance will be read from the command-line. Here s a typical use of the program: findvals -r -6.77 -t 0.25 This should report a count of all of the numbers encountered that are within ±0.25 of -6.77, the given reference value. 1 Before going any further have a poke around this week s class directory and run the sample executable there on some of the sample inputs. Make sure and have a look at the input files that are given there. For example, you might want to try ls -l ~cs4023/labs/week06 followed by, say, ~cs4023/labs/week06/findvals -r 5.6 -t 23.0 < ~cs4023/labs/week06/mat.100x50 and then, just for comparison ~cs4023/labs/week06/findvals -r 5.6 -t 230.0 < ~cs4023/labs/week06/mat.100x50 The format of the output that you see will be the format I expect so please pay close attention to how the output is formatted. Where to start? From last time you should be able to test for the arguments -r and -t using strcmp(). (I haven t said which order the two come in, though and you should be able to handle either order.) Converting strings into numbers From last time we also know that in the above example argv[2], the third element of argv, will contain a memory address. At this memory address will be the string of characters -6.77. Our first job is to convert the string -6.77 to the number -6.77. For this we need the C library function strtof() that converts a string to a floating point no. This function returns a floating point no. that the string of characters represents. Please do man strtof and read the first couple of paragraphs. You are now in a position to write the first couple of lines of the program that processes the command-line arguments and figures out ref, the reference value of interest to us, and tol, the acceptable tolerance. The next task is to read the matrix of numbers to search. 1 Note that you may get different results from your program if you run it on a 32-bit machine or a 64-bit machine even if you use the same input data. This is because of the differing numerical precision between the two machine types. 2

Reading a number When you read an input value into a variable say, x you are inserting the some of the contents of the input stream into the memory location that we call x. The C function to read from the keyboard is scanf(). It takes two arguments: the first one tells it what type of thing it should be reading (int, float, double, char, etc.) and then it needs to be told where to put the thing. For the latter you might think that you should give x but on a moment s reflection you will realise that what it needs is where to put it so what scan needs as its second argument is the address of x. This is achieved with &x. The address of operator & and the pointer dereference operator * are fellow travellers. input from keyboard To read a value from the keyboard into an int variable you need to specify where the result should go that is, the address in memory of where the identifier is located. If x is of type int, then to read a value into x we write: scanf("%d", &x) To read a floating-point number into y we write: scanf("%f", &y) Input redirection But where do you get your data stream from? I have made no mention of reading a file given as a command line argument... Enter one of UNIX s most powerful facilities. If your program expects data to be entered from the keyboard then, with the assistance of the shell, we can fool our program into thinking it is reading from the keyboard. This is known as input redirection. So rather than having to bother with opening and reading filenames specified on the command-line we can just rely on reading from standard input or stdin, as it is known in C programs. 3

input / output redirection Suppose you have a program that reads data from the keyboard and writes results to the screen. If a lot of data needs to be entered then running the program multiple times will surely wear you out. With the help of the shell you can redirect the source of input to come from a file; likewise, you can redirect your output to a file so that you can save it for later use. In the present context, our program findvals expects input (a matrix of numbers) from the keyboard. findvals -r -6.77 -t 0.25 However, if we have a matrix of numbers already saved in the file mtx we can do findvals -r -6.77 -t 0.25 < mtx and our program is happy out. Speaking of out, we can save the output from our program with findvals -r -6.77 -t 0.25 < mtx > results and the output of the program is saved to the file results for later examination. Allocating space for the matrix There is no point in attempting to guess maximum likely sizes for the size of the matrix: we ll get it wrong sooner or later. So, the more general solution is to wait until run-time and be told how big the array will be for this run of the program. The first input your program will receive, then, will be a pair of numbers (two ints) that let you know the size of the matrix to follow: r rows, c columns. You should then prepare for reading those rc floating-point numbers. In C two-dimensional arrays only exist as an array of arrays. That is, each row of the matrix we read in will be stored as a one-dimensional array of size c. To reinforce that point here s the way that you access the element at row i and column j of the matrix arr and assign 2 to it: arr[i][i] = 2; So what we do is ask the OS for a memory allocation the system call is malloc() that will accommodate c floats. malloc() returns a pointer to the block of memory if it can and returns 0 if it can t. We do this r times, one for each row. But we also need to remember each row that we ve requested space for! 4

Here s how I set up the code to request a memory allocation to store an (rct cct) matrix of floats note error checking if malloc() cannot satisfy a memory request: float** rows = (float **) malloc(rct * sizeof(float *)); if (rows == 0) { fprintf(stderr, "Couldn t alocate sufficient space.\n"); exit(1); } int i; for (i = 0; i < rct; i++) { float* row = (float *) malloc(cct * sizeof(float)); if (row == 0) { fprintf(stderr, "Couldn t alocate sufficient row space.\n"); exit(1); } rows[i] = row; } Requesting an array of arrays in C Reading the matrix With all that under your belt you can now easily read in your matrix of numbers into the data structure that rows points to. You simply write two nested for-loops with indices i and j; index i ranges over the rows and, nested within, the for-loop indexed by j, ranges over each element of that row. There is a single line of code at the heart of the two nested loops and this reads a single float of the matrix: scanf("%f", &rows[i][j]; Et voilà. The matrix has been read into the array (of arrays) rows. Note that no matter how the data looks in the file the array gets filled as first c values go in to first row, next c values into next row, etc. That is, the scanf() function ignores any white space, new lines, etc. You should now be able to write code to determine from the command-line value and tolerance, the two required parameters and convert these to floating point numbers read from stdin the row and column dimensions of the matrix to follow 5

allocate sufficient memory in the form of a one-dimensional array for each row and an additional vector that allows us to index these rows read in the entire matrix via two nested for-loops Testing each element You should now take your utils.c file from last time, copy it into this week s lab directory, and add to it by writing a function approxequal(). This function takes three arguments, the two values to compare and the allowed tolerance. Once you have read in the matrix in its entirety you will use this function in order to iterate over the matrix, comparing each element against the reference value and the allowable tolerance. If you get a hit in addition to keeping track of the number of them you should also print out the row index, column index and value where the hit was found. The syntax for this is: fprintf(stdout, "r=%d, c=%d: %.6f\n", r, c, rows[r][c]); Printing time/date information Although the UNIX utility time can be very useful to check the amount of time a program runs for, sometimes we want to know more specific things about how long various parts of code runs for. Or, related, we might want to log what time the program started at. Here s some code that can achieve these tasks. The following code will a) record the number of seconds elapsed since the beginning of time, b) convert this no. of seconds to a date and, c) print out this date. #include <time.h> struct tm *local; time_t start, end; time(&start); // read and record clock local = localtime(&start); printf("# Start time and date: %s", asctime(local)); Using struct time t in C You should add to this code now so that it logs the finish time also. ❹ This is the third lab that you will be assessed on. To be assessed you will need to have the program written and working properly by 16.00, Thu. Week07. The command for submitting this lab via the handin mechanism is: handin -m cs4023 -p w06 6