Programming Assignment #4 Arrays and Pointers

Similar documents
Programming Assignment #3 Event Driven Simulation

C Functions. 5.2 Program Modules in C

Lecture 04 FUNCTIONS AND ARRAYS

Function Call Stack and Activation Records

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

EAS230: Programming for Engineers Lab 1 Fall 2004

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

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

Chapter 5 C Functions

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

CSE123. Program Design and Modular Programming Functions 1-1

Using pointers with functions

Two Dimensional Array - An array with a multiple indexs.

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Project 4: Implementing Malloc Introduction & Problem statement

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

ECE15: Lab #4. Problem 1. University of California San Diego

Laboratory Assignment #3 Eclipse CDT

CS 150 Lab 10 Functions and Random Numbers

ECE15: Lab #3. Problem 1. University of California San Diego ( 1) + x4. + x8 + (1)

C++ PROGRAMMING SKILLS Part 4: Arrays

Functions and Recursion

CS 241 Data Organization. August 21, 2018

Laboratory Assignment #4 Debugging in Eclipse CDT 1

Arrays and Pointers in C & C++

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Two Dimensional Array - An array with a multiple indexs.

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C: How to Program. Week /Apr/23

Functions in C C Programming and Software Tools

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

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

Introduction to Computer Science Midterm 3 Fall, Points

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

EECE.2160: ECE Application Programming

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September

C Arrays Pearson Education, Inc. All rights reserved.

Programming Standards: You must conform to good programming/documentation standards. Some specifics:

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Assignment #3 Answers

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

LAB: WHILE LOOPS IN C++

Programming for Engineers Functions

Chapter 6 - Pointers

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

AMCAT Automata Coding Sample Questions And Answers

SPRING 2017 CSCI 304 LAB1 (Due on Feb-14, 11:59:59pm)

Physics 2660: Fundamentals of Scientific Computing. Lecture 7 Instructor: Prof. Chris Neu

CS 241 Data Organization using C

C Functions Pearson Education, Inc. All rights reserved.

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Programming Assignment IV Due Thursday, June 1, 2017 at 11:59pm

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

1. Introduction. 2. Deliverables

Programming Tips for CS758/858

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CpSc 1111 Lab 9 2-D Arrays

Project 1. due date Sunday July 8, 2018, 12:00 noon

Project Data: Manipulating Bits

Programming Assignment 2

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Computer Science & Engineering 150A Problem Solving Using Computers

Writing to and reading from files

CS201 - Introduction to Programming FAQs By

Objectives of This Chapter

CS : Programming for Non-majors, Summer 2007 Programming Project #2: Census Due by 12:00pm (noon) Wednesday June

Course Information and Introduction

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

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

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

C Programs: Simple Statements and Expressions

CSE 351, Spring 2010 Lab 7: Writing a Dynamic Storage Allocator Due: Thursday May 27, 11:59PM

COMP 110 Programming Exercise: Simulation of the Game of Craps

Project #1: Tracing, System Calls, and Processes

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

CS 361 Computer Systems Fall 2017 Homework Assignment 1 Linking - From Source Code to Executable Binary

PRINCIPLES OF OPERATING SYSTEMS

Programming Assignment Multi-Threading and Debugging 2

Chapter 4 Functions By C.K. Liang

Computer Science & Engineering 150A Problem Solving Using Computers

Lab 4: Tracery Recursion in C with Linked Lists

Lab Instructor : Jean Lai

Welcome to... CS113: Introduction to C

Programming assignment A

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

ENCE 3241 Data Lab. 60 points Due February 19, 2010, by 11:59 PM

CMSC 201 Fall 2016 Homework 6 Functions

CS1110 Lab 6 (Mar 17-18, 2015)

Project 2: Buffer Manager

ECET 264 C Programming Language with Applications

CS 470 Operating Systems Spring 2013 Shell Project

CSC101 - BMCC - Spring /22/2019. Lab 07

Project 5 Handling Bit Arrays and Pointers in C

Calling Prewritten Functions in C

CME 112- Programming Languages II. Week 1 Introduction, Scope Rules and Generating Random Numbers

Transcription:

CS-2301, System Programming for Non-majors, B-term 2013 Project 4 (30 points) Assigned: Tuesday, November 19, 2013 Due: Tuesday, November 26, Noon Abstract Programming Assignment #4 Arrays and Pointers Develop a Monte Carlo simulation of the game of craps to learn more about the game s behavior. Outcomes After successfully completing this assignment, you should be able to: Create arrays of data Pass arrays as arguments to functions Allow functions to modify the contents of arrays Use pointer arithmetic for arrays Build a multi-file application in C Use makefiles to correctly build, rebuild, and clean your working directory Background Read the sections of your textbook on pointers and arrays. To better understand the Bubble Sort algorithm, consult Wikipedia or other resources. A Monte Carlo simulation is a program that runs many times with random inputs in order to gather a statistical picture of its outputs. Monte Carlo simulations are widely used in business and engineering when it is impossible or too difficult to model problems, systems, investment strategies, etc., or when the problems have too many degrees of freedom for an analysis in closed form. In this assignment, the problem is the game of craps. Your program should enable you to discover how frequently the player wins versus loses, whether a game with many rolls of the dice favors the player or the house, and other useful information that a gambler would like to know. This Assignment Create a new program called montecarlo based on at least three C files, two header files, and one makefile. Copy the functions playgame and rolldice from Programming Assignment #3 into a new file named, for example, playcraps.c. Create a new header file, playcraps.h, that contains the function prototype of playgame and anything else needed by a caller of playgame for example, to initialize (i.e., seed ) the random number generator. Modify playgame so that (a) it does not print anything, and (b) it returns an integer reflecting both the number of throws of the dice and whether the game was won or lost. In particular, if the player wins a game after n throws, it should return the integer value n. If the player loses after n throws, it should return the integer value n. Project 4 1

In one or more new.c files, create the following functions: A function that prompts the user for the number of games of craps to play and then plays that number of games without human intervention (i.e., by calling playgame). It stores the results of the games in an appropriately-sized array, one element per game. In particular, the number of elements in the array should be exactly the number of games entered by the user. A function to print out the number of games played and compute the mean and median numbers of throws required for a game to be won or lost. A function to analyze the array of results and print out answers to the questions listed below. The main() function, that controls all of the others. In particular, main or one of the functions it calls must allocate and free any arrays that it needs. Construct a makefile patterned after Lab #4 to build the montecarlo program and all of its components. Make sure that $(CFLAGS) is specified in the commands to build individual modules and that it defaults to g -Wall. Be sure that your makefile rebuilds only those files that are necessary and that it can make your directory clean. For the analysis portion of this assignment, your program needs to print out answers to the following questions: 1. What is the probability that the player wins a game of craps? 2. What percentage of games are won on the first throw, second throw, third throw,, twentieth throw, and after the twentieth throw? (The sum of these percentages should total to the probability in Question 1, expressed as a percentage.) 3. What percentage of games are lost on the first throw, second throw, third throw,, twentieth throw, and after the twentieth throw? (The sum of these percentages, when added to the probability in Question 1 expressed as a percentage, should total 100%.) 4. Do the chances of winning improve with the length of the game? In particular, for questions 2 and 3, print out a table showing the number of throws and for each number of throws, the percentages of games with that number of throws that are won and lost. You may need to construct another array to generate this data. Test and debug your program with at least 1000 games. After you have debugged your program, modify it to seed the random number generator with the time of day and test it again. Be sure that the program you turn in is seeded with the time. Finally, run the program 8 times, saving the output in a file, with two runs each of 100, 500, 1000, and 5000 games. Turn this file in with your program and README file, and in the README file summarize what you see in these experiments. What sort of differences do you see when repeating with the same number of games and different seeds? What variability do you see as you increase the number of games? Include Files needed by your Programs stdio.h provides printf, scanf, getchar stdlib.h provides rand, srand, and abs math.h provides sqrt time.h provides time, which is used to seed the random number generator You may wish to consult the man pages for some these functions. In a Linux command shell (e.g., your PuTTY, X-Win32, or SSH window), type man abs man rand man srand Project 4 2

man sqrt Note that the time function is a little different in the man page system, because there are several of them. If you simply type man time, you will get information for the time shell command i.e., a command that tells you how long it takes to execute another command. This is not what you want. Instead, type man 2 time This tells the man page system to give you information about time function defined in Section 2 of the man pages, where most of the functions are defined. In general, if you simply ask the man page system for information about command xyz, it will provide you with the information matching xyz in the lowest numbered section. If you want something from another section, you have to specifically provide the section number. More information about the man page system can be found by typing the following to a Linux command prompt: man man man apropos Means and Medians and Standard Deviations Means, medians, and standard deviations are commonly used in engineering and scientific calculations. The mean number of throws is easy to calculate. Simply add up the number of throws in the array and divide by the number of games. Be sure you take the absolute value of the number of throws, so that losing games do not cancel winning ones. To calculate the median, you must sort the array. If a sorted array A has n elements, the median is defined as A[n/2] if n is odd and as (A[n/2-1] + A[n/2])/2.0 if n is even. (This particular definition of the median is based on the fact that arrays in C are indexed from zero.) You may sort the array using the Bubble Sort algorithm, shown here: void BubbleSort (int A[], const int arraysize) { int i, j; for(i = 0; i < arraysize; i++) for(j = 0; j < arraysize-1; j++) if(abs(a[j]) > abs(a[j+1])) swap(a+j, A+j+1); } // void BubbleSort( ) Note that this algorithm sorts the array A in place. Note also that it sorts by the absolute values of the elements of A. Finally, note that it uses array arithmetic to pass pointers to the swap function. The swap function is void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // void swap( ) It is best to put the BubbleSort and swap functions in its own.c file called bubblesort.c. To make BubbleSort available, there should also be a bubblesort.h file. Note that the swap function should not be mentioned in bubblesort.h, because that is strictly internal to the implementation of Bubble Sort and won t be called independently by any other program. Project 4 3

The standard deviation is the square root of the variance. The variance is the average of the squared distance between each value and its mean. Thus with count entries in the list and a mean value of ave, the variance = [ ] /count. The square root function sqrt() expects a double value as input and returns a double value. Deliverables You should write a short README file in.txt,.doc, or.pdf format, to be submitted with your program. In this file, you should document the pre- and post-conditions of all functions and the loop invariants of all loops. You should also include your analysis of the data file from your experiments. This assignment is named PA4 in the web-based Turnin system. You can access Turnin from any browser at the following URL: https://turnin.cs.wpi.edu:8088. Be sure to put your name at the top of ALL files, including all code, header, and data files! You would be surprised by how many students forget this. Programs submitted after Noon on November 26 will be tagged as late, and will be subject to the late assignment policy. Grading This assignment is worth thirty (30) points. Your program must compile without errors in order to receive any credit. It is suggested that before your submit your program, compile it again on a CCC system to be sure that it does not blow up or contain surprising warnings. Program organization into three or more.c files, two or more.h file(s), and a makefile 4 points. Note: The.c files should include at least playgame.c (or whatever you wish to call it), the new.c file that sets up the array and plays the requested number of games, and your sort function (Bubblesort or otherwise). The first target of the makefile should be a program file called montecarlo. Correct compilation without warnings using make and correct operation of make for individual files and for clean 4 points Correctly allocating an array of n elements, correctly playing the game n times, correctly storing the results in the array, correctly freeing the array at the end 5 points Correctly sorting the array and obtaining the mean, median, and standard deviation on the number of throws 4 points Building a table or other suitable data structure to answer the four questions, printing out those results, and getting answers consistent with the TAs test cases 5 points Creating a data file with the output of 8 runs of your program 4 points Satisfactory README file, including loop invariants for all loops and pre-and post-conditions on all functions and analysis of data 4 points In addition, the correct usage of a makefile to build your system completes the requirements of Lab 4. Extra credit For five points extra credit, modify your main program to accept two optional command line arguments according to 5.10 of Kernighan and Ritchie. The command line arguments are numberof- Games and SeedValue. If one argument is specified, don t prompt the user for the number of games, but simply use the number in the command argument and print out a message saying so. If a Project 4 4

second argument is specified, use its number as the seed instead of the time. For example, your command line might be./montecarlo 1000 23546 This instructs montecarlo to play 1000 games and to seed the random number generator with the value 23456. As with all assignments, be sure to get the required part of the assignment working before attempting to modify it to accept command line arguments. Project 4 5