6.096 Problem Set 2. Due: 14 January 12:30:00

Similar documents
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Basics of I/O Streams and File I/O

arrays C Programming Language - Arrays

Chapter One Introduction to Programming

Sources: On the Web: Slides will be available on:

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Member Functions of the istream Class

An Incomplete C++ Primer. University of Wyoming MA 5310

Passing 1D arrays to functions.

Chapter 5 Functions. Introducing Functions

The While Loop. Objectives. Textbook. WHILE Loops

5 Arrays and Pointers

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

NUMBER SYSTEMS APPENDIX D. You will learn about the following in this appendix:

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

SAT Math Facts & Formulas Review Quiz

Informatica e Sistemi in Tempo Reale

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Lab 11. Simulations. The Concept

Base Conversion written by Cathy Saxton

Comp151. Definitions & Declarations

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Object Oriented Software Design II

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Object Oriented Software Design II

To convert an arbitrary power of 2 into its English equivalent, remember the rules of exponential arithmetic:

The C Programming Language course syllabus associate level

Goals for This Lecture:

CHM 579 Lab 1: Basic Monte Carlo Algorithm

if and if-else: Part 1

Stacks. Linear data structures

1 Description of The Simpletron

Ready, Set, Go! Math Games for Serious Minds

Sequential Program Execution

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Lecture 2 Notes: Flow of Control

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Introduction to Data Structures

Common Data Structures

3 Some Integer Functions

AP Computer Science Java Mr. Clausen Program 9A, 9B

1.6 The Order of Operations

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Math 115 Spring 2011 Written Homework 5 Solutions

Supplemental Worksheet Problems To Accompany: The Pre-Algebra Tutor: Volume 1 Section 1 Real Numbers

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Answers to Review Questions Chapter 7

Curriculum Map. Discipline: Computer Science Course: C++

Node-Based Structures Linked Lists: Implementation

6. Control Structures

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Parameter passing in LISP

Functions and Parameter Passing

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

C++ Overloading, Constructors, Assignment operator

C++ INTERVIEW QUESTIONS

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Lab Experience 17. Programming Language Translation

Unit 6. Loop statements

Pseudo code Tutorial and Exercises Teacher s Version

VHDL Test Bench Tutorial

CS 111 Classes I 1. Software Organization View to this point:

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Conversion Constructors

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

Lab 2: Swat ATM (Machine (Machine))

Pemrograman Dasar. Basic Elements Of Java

Habanero Extreme Scale Software Research Project

Student Outcomes. Lesson Notes. Classwork. Discussion (10 minutes)

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

The programming language C. sws1 1

C++ Input/Output: Streams

1 Abstract Data Types Information Hiding

Lecture 22: C Programming 4 Embedded Systems

C++ Language Tutorial

Chapter 5 Names, Bindings, Type Checking, and Scopes

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Moving from CS 61A Scheme to CS 61B Java

Storing Measurement Data

Lecture Notes on Binary Search Trees

C++FA 5.1 PRACTICE MID-TERM EXAM

Formatting Numbers with C++ Output Streams

Recursion vs. Iteration Eliminating Recursion

COMPUTER SCIENCE. Paper 1 (THEORY)

Java Interview Questions and Answers

Julie Rotthoff Brian Ruffles. No Pi Allowed

Linked Lists: Implementation Sequences in the C++ STL

F ahrenheit = 9 Celsius + 32

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

Transcription:

6.096 Problem Set Due: 14 January 1:30:00 For this problem set, you should be able to put all your code for each section into a single source/text file (though you may have to comment out earlier parts of your solution to test later parts). Clearly mark each subsection with comments, and submit a.zip file containing all your source/text files. 1 Additional Material 1.1 Functions 1.1.1 Default Arguments Say you have a function with 1 argument, but that argument is usually the same. For instance, say we want a function that prints a message n times, but most of the time it will only need to print it once: 1 void printntimes( char *msg, int n) { for ( int i = 0; i < n; ++i) { 3 cout << msg; 4 } 5 } Rather than writing printntimes("some message", 1); every time, C++ allows default arguments to be defined for a function: 1 void printntimes ( char *msg, int n = 1) { for ( int i = 0; i < n; ++ i) { 3 cout << msg ; 4 } 5 } Declaringthefunction argumentas int n = 1 allows usto callthefunction with printntimes("some message");. The compiler automatically inserts 1 as the second argument. You may have multiple default arguments for a function: 1 void printntimes( char *msg = "\n", int n = 1) { for ( int i = 0; i < n; ++i) { 3 cout << msg; 1

4 } 5 } Now, to print one newline, we can simply write printntimes();. However, C++ does not allow skipping arguments, so we could notprint k newlinesby writing printntimes(k);. To do that, we d need to say printntimes("\n", k);. 1.1. Constant Arguments It s often useful to specify that arguments to a function should be treated as constants. As with regular variables, we can declare function arguments to be const: 1 void print( const int n) { cout << n; 3 } This is particularly useful when we are passing values by reference to a function, but don t want to allow the function to make any changes to the original value: 1 void print( const long &x) { // Pass -by -reference avoids overhead // of copying large number 3 cout << x; 4 } 5 6 int main() { 7 long x = 349359; 8 print(x); // We are guaranteed that x 9 // will not be changed by this 10 return 0; 11 } In general, if you know a value shouldn t be changing (particularly a function argument), you should declare it const. That way, the compiler can catch you if you messed up and tried to change it somewhere. 1.1.3 Random Number Generation Functions The C++ standard libraries include the rand() function for generating random numbers between 0 and RAND MAX (an integer constant defined by the compiler). These numbers are not truly random; they are a random-seeming but deterministic sequence based on a particular seed number. To make sure we don t keep getting the same random-number sequence, we generally use the current time as the seed number. Here is an example of how this is done: 1 #include <iostream > #include <cstdlib > // C standard library 3 // defines rand(), srand(), RAND_MAX

4 #include <ctime> // C time functions - defines time() 5 int main() { 6 srand( time(0) ); // Set the seed; 7 // time(0) returns current time as a number 8 int randnum = rand(); 9 std::cout << "A random number: " << randnum << endl; 10 return 0; 11 } 1. Pointers 1..1 Pointers to Pointers We can have pointers to any type, including pointers to pointers. This is commonly used in C (and less commonly in C++) to allow functions to set the values of pointers in their calling functions. For example: 1 void setstring( char **strptr) { int x; 3 cin >> x; 4 if (x < 0) 5 *strptr = "Negative!"; 6 else 7 *strptr = "Nonnegative!"; 8 } 9 10 int main() { 11 char *str; 1 setstring(&str); 13 cout << str; // String has been set by setstring 14 return 0; 15 } 1.. Returning Pointers When you declare a local variable within a function, that variable goes out of scope when the function exits: the memory allocated to it is reclaimed by the operating system, and anything that was stored in that memory may be cleared. It therefore usually generates a runtime error to return a pointer to a local variable: 1 int 3 4 } 5 * getrandnumptr () int x = rand () ; return &x; { 3

6 int main() { 7 int *randnumptr = getrandnumptr(); 8 cout << *randnumptr; // ERROR 9 return 0; 10 } Line 8 will likely crash the program or print a strange value, since it is trying to access memory that is no longer in use x from getrandnumptr has been deallocated. 1.3 Arrays and Pointers 1.3.1 Arrays of Pointers Arrays can contain any type of value, including pointers. One common application of this is arrays of strings, i.e., arrays of char * s. For instance: 1 const char *suitnames[] = {"Clubs ", "Diamonds ", "Spades ", "Clubs "}; cout << "Enter a suit number (1-4): "; 3 unsigned int suitnum; 4 cin >> suitnum; 5 if (suitnum <= 3) 6 cout << suitnames[suitnum - 1]; 1 3 4 1.3. Pointers to Array Elements It is important to note that arrays in C++ are pointers to continuous regions in memory. Therefore the following code is valid: const int ARRAY_LEN = 100; int arr [ ARRAY_LEN ]; int *p = arr ; int *q = & arr [0]; Now p and q point to exactly the same location as arr (ie. arr[0]), and p, q and arr can be used interchangeably. You can also make a pointer to some element in the middle of an array (similarly to q): 1 int *z = &arr[10]; 1.4 Global Scope We discussed in lecture how variables can be declared at global scope or file scope if a variable is declared outside of any function, it can be used anywhere in the file. For anything besides global constants such as error codes or fixed array sizes, this is usually a bad idea; if you need to access the same variable from multiple functions, most often you should simply 4

pass the variable around as an argument between the functions. Avoid global variables when you can. A Simple Function What would the following program print out? (Answer without using a computer.) 1 void f( const int a = 5) { 3 std :: cout << a * << "\n"; 4 } 5 6 int a = 13; 7 int main () 8 { 9 f (1) ; 10 f(a); 11 int b = 3; 1 f(b); 13 int a = 4; 14 f(a); 15 f () ; 16 } 3 Fix the Function Identify the errors in the following programs, and explain how you would correct them to make them do what they were apparently meant to do. 3.1 1 #include <iostream > 3 int main() { 4 printnum(35); 5 return 0; 6 } 7 8 void printnum( int number) { std::cout << number; } (Give two ways to fix this code.) 5

3. 1 #include <iostream > 3 void printnum() { std::cout << number; }; 4 5 int main() { 6 int number = 35; 7 printnum(number); 8 return 0; 9 } (Give two ways to fix this code. Indicate which is preferable and why.) 3.3 1 # include <iostream > 3 void doublenumber ( int num ) { num = num * ;} 4 5 int main () { 6 int num = 35; 7 doublenumber ( num ); 8 std :: cout << num ; // Should print 70 9 return 0; 10 } (Changing the return type of doublenumber is not a valid solution.) 3.4 1 #include <iostream > #include <cstdlib > // contains some math functions 3 4 int difference( const int x, const int y) { 5 int diff = abs(x - y); // abs(n) returns absolute value of n 6 } 7 8 int main() { 9 std::cout << difference(4, 138); 10 return 0; 11 } 6

3.5 1 # include <iostream > 3 int sum ( const int x, const int y) { 4 return x + y; 5 } 6 7 int main () { 8 std :: cout << sum (1,, 3) ; // Should print 6 9 return 0; 10 } 3.6 1 #include <iostream > const int ARRAY_LEN = 10; 3 4 int main() { 5 int arr[array_len] = {10}; // Note implicit initialization of 6 // other elements 7 int *xptr = arr, yptr = arr + ARRAY_LEN - 1; 8 std::cout << *xptr << << *yptr; // Should output 10 0 9 return 0; 10 } 4 Sums Make sure to use const arguments where appropriate throughout this problem (and all the others). 4.1 Write a single sum function that returns the sum of two integers. Also write the equivalent function for taking the sum of two doubles. 4. Explain why, givenyourfunctionsfrompart1, sum(1, 10.0) is a syntax error. (Hint: Think about promotion and demotion the conversion of arguments between types in a function call. Remember that the compiler converts between numerical types for you if necessary.) [1 point] 7

4.3 Write more functions such that you can find the sum of anywhere between and 4 integers by writing sum(num1, num,...). 4.4 Now write just one function that, using default arguments, allows you to take the sum of anywhere between and 4 integers. What would happen if you put both this definition and your 3-argument function from part 3 into the same file, and called sum(3, 5, 7)? Why? 4.5 Write a single sum function capable of handling an arbitrary number of integers. It should take two arguments, include a loop, and return an integer. (Hint: What data types can you use to represent an arbitrarily large set of integers in two arguments?) 4.6 Now rewrite your function from 4.5 to use recursion instead of a loop. The function signature should not change. Thinking about pointer arithmetic may help you. 5 Calculating π This problem is a bit tricky, but it s a good exercise in writing a program that actually does something neat. It will also familiarize you with using random numbers. Using a Monte Carlo method that is, a randomized simulation we can compute a good approximation of π. Consider a circle of radius 1, centered on the origin and circumscribed by a square, like so: }1 Imagine that this is a dartboard and that you are tossing darts at it randomly. With enoughdarts, the ratio ofdartsinthe circletototaldartsthrown shouldbe the ratiobetween total darts 4 the area of the circle (call it a) and the area of the square (4): =. We can use darts in circle a a this ratio to calculate a, from which we can then find π =. r We can simplify the math by only considering the first quadrant, calculating the ratio of a the top right square s area to the area of the single quadrant. Thus, we will actually find and then compute π = 4 r 4. We ll build a function step by step to do all this. a 8 4,

5.1 Define variables to store the x and y coordinates of a particular dart throw. Initialize them to random doubles in the range [0, 1] (simulating one dart throw). (Hint: remember that rand() returns a value in the range [0, RAND MAX]; we just want to convert that value to some value in [0, 1].) 5. Place your x and y declarations in a loop to simulate multiple dart throws. Assume you have a variable n indicating how many throws to simulate. Maintain a count (declared outside the loop) of how many darts have ended up inside the circle. (You can check whether a dart is within a given radius with the Euclidean distance formula, d = x +y ; you may find the sqrt function from the <cmath> header useful.) 5.3 Now use your loop to build a π-calculating function. The function should take one argument specifying the number of dart throws to run (n from part ). It should return the decimal value of pi, using the technique outlined above. Be sure to name your function appropriately. Don t forget to initialize the random number generator with a seed. You should get pretty good results for around 5,000,000 dart throws. 6 Array Operations 6.1 Write a function printarray to print the contents of an integer array with the string ", " between elements (but not after the last element). Your function should return nothing. 6. Write a reverse function that takes an integer array and its length as arguments. Your function should reverse the contents of the array, leaving the reversed values in the original array, and return nothing. 6.3 Assumethe existence oftwo constants WIDTH and LENGTH.Write afunction withthefollowing signature: void transpose( const int input[][length], int output[][width]); 9

Your function should transpose the WIDTH LENGTH matrix in input, placing the LENGTH WIDTH transposed matrixinto output. (Seehttp://en.wikipedia.org/wiki/Transpose#Examples for examples of what it means to transpose a matrix.) 6.4 What would happen if, instead of having output be an out argument, we simply declared a new array within transpose and returned that array? 6.5 Rewrite your function from part to use pointer-offset notation instead of array-subscript notation. 7 Pointers and Strings 7.1 Write a function that returns the length of a string (char *), excluding the final NULL character. It should not use any standard-library functions. You may use arithmetic and dereference operators, but not the indexing operator ([]). 7. Write a function that swaps two integer values using call-by-reference. 7.3 Rewrite your function from part to use pointers instead of references. 7.4 Write a function similar to the one in part 3, but instead of swapping two values, it swaps two pointers to point to each other s values. Your function should work correctly for the following example invocation: 1 int x = 5, y = 6; int * ptr1 = &x, * ptr = &y; 3 swap (& ptr1, & ptr ); 4 cout << * ptr1 << << * ptr ; // Prints "6 5" 10

7.5 Assume that the following variable declaration has already been made: 1 char *oddoreven = "Never odd or even "; Write a single statement to accomplish each of the following tasks (assuming for each one that the previous ones have already been run). Make sure you understand what happens in each of them. 1. Create a pointer to a char value named nthcharptr pointing to the 6th character of oddoreven (remember that the first item has index 0). Use the indexing operator.. Usingpointerarithmetic,update nthcharptr topointtothe4th characterin oddoreven. 3. Print the value currently pointed to by nthcharptr. 4. Create a new pointer to a pointer (a char **) named pointerptr that points to nthcharptr. 5. Print the value stored in pointerptr. 6. Using pointerptr, print the value pointed to by nthcharptr. 7. Update nthcharptr to point to the next character in oddoreven (i.e. one character past the location it currently points to). 8. Using pointer arithmetic, print out how far away from the character currently pointed to by nthcharptr is from the start of the string. 11

MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 011 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.