Comp 201 LabsSpring 2012

Comp 201 LabsSpring 2012Prof. M Werner

(Subject to change)

Lab Submission Rules

1.Lab grades are 0 .. 10, with 10 representing a correct lab turned in on time.

2.Labs lose 2 points for each week late. Labs 5 or more weeks late are not accepted.

3.Labs are submitted as a single MS Word document. The document includes:

  • A heading clearly identifying the lab assignment, your name and the submission date.
  • Problem statement (you can summarize).
  • Brief analysis of the problem specifying inputs, processing and outputs.
  • Design charts as specified by the instructor. These will usually be structure charts or flow charts.
  • Source file(s)
  • Output from sample runs

4.Labs are normally submitted by Blackboard. The back-up is to submit as an e-mail attachment to . Do not submit executables or other unreadable files.

6.Labs are to be done individually.

7.Lab Grades:

Points
Analysis / Identify requirements (usually outputs), inputs and processing / 2
Design / Include a correct chart as specified. Your code must conform to the chart. / 2
Correctness / Include test runs verifying that the program produces correct outputs / 4
Programming style / Is the code straight-forward, terse, readable, properly indented? / 2

Model Lab Submission (as a word doc)

/*********************************************************************

*Lab 8 Problem 1

*Melissa Mooney

*COMP201-00

*Jan 21, 2012

**********************************************************************

*Problem: Some languages such as German use more capitalization

*thanother languages which share the same alphabet. To check

*this, a program is needed to read through a text file and

*calculate the percentage of letters that are capitalized.

***********************************************************************

*Analysis

*

*Inputs: A pre-existing text file

*The name of the file (including the path)

*Output: The percentage of letters that are capitalized

*Error message if the named file cannot be opened

***********************************************************************

*Design

*

*Get file name from user

*Open the file. If this fails give error message and die

*Zero CapsCount, LowersCount

*Scan the file char-by-char

*if capital capsCount++

*if lower lowersCount++

*Divide CapsCount by LowersCount

*Output result as a percent

*

*See attached structure chart for functional decomposition

**********************************************************************/

#include <iostream>

#include <fstream>

using namespace std;

double processFile(ifstream& in);

bool isCap(char c);

bool isLower(char c);

int main(){

char filename[128];

ifstream in;

cout < "Enter filename: ";

cin > filename;

in.open(filename);

if(!in.is_open()){

cout < "Failed to open " < filename < endl;

cout < "Now exiting\n";

exit(-1);

}

double ratio = processFile(in);

cout < "The percentage of letters that are capitalized is "

< ratio*100 < '%'< endl;

return 0;

}

double processFile(ifstream& in){

char c;

int capsCount = 0;

int lowersCount = 0;

while(in > c){ //skips white space

if(isCap(c))

capsCount++;

elseif(isLower(c))

lowersCount++;

//non-letters are ignored

}

returnstatic_castdouble>(capsCount)/(lowersCount + capsCount);

}

bool isCap(char c){

return c >= 'A' & c <= 'Z';

}

bool isLower(char c){

return c >= 'a' & c <= 'z';

}

/* Sample run

Enter filename: C:\Temp\Jabberwocky.txt

The percentage of letters that are capitalized is 5.84046%

Press any key to continue . . .

*/

Jabberwocky by Lewis Carroll

10/8/20181Prof. M Werner

Comp 201 LabsSpring 2012

'Twas brillig, and the slithy toves

Did gyre and gimble in the wabe:

All mimsy were the borogoves,

And the mome raths outgrabe.

"Beware the Jabberwock, my son!

The jaws that bite, the claws that catch!

Beware the Jubjub bird, and shun

The frumious Bandersnatch!"

He took his vorpal sword in hand:

Long time the manxome foe he sought—

So rested he by the Tumtum tree,

And stood awhile in thought.

And, as in uffish thought he stood,

The Jabberwock, with eyes of flame,

Came whiffling through the tulgey wood,

And burbled as it came!

One, two! One, two! And through and through

The vorpal blade went snicker-snack!

He left it dead, and with its head

He went galumphing back.

"And hast thou slain the Jabberwock?

Come to my arms, my beamish boy!

O frabjous day! Callooh! Callay!"

He chortled in his joy.

'Twas brillig, and the slithy toves

Did gyre and gimble in the wabe:

All mimsy were the borogoves,

And the mome raths outgrabe.

10/8/20181Prof. M Werner

Comp 201 LabsSpring 2012

Lab 1 due Jan 20 – Review of functions, loops, decisions

  1. We consider numbers to be red, green or yellow. Negative numbers are red, numbers in the range 0.0 .. 1.0 are green and numbers larger than 1.0 are yellow. Write a program to read through a file of floating point numbers and count how many are red, green and yellow. Write a function named color() which is passed a double and returns 0 if red, 1 if green, and 2 if yellow. The main() function should open the file and print the answers. A function named process() should scan the numbers one-by-one, pass the number to color and increment the appropriate count. Include a structure chart as in the model lab.

2.Write a program to reverse capitalize all the letters in a text file, ie. capital letters are made lower case and lower case letters made capitals. Use 2 files: an input file for the original text, and an output file for the reverse-capitalized text. Include a structure chart as in the model lab.

Lab 2 due Jan 27 – Arrays and Sorting

1.Computing a standard deviation. Refer to p. 435 Programming Project 4. Notice that computing a standard deviation requires 2 passes through the array, the first pass computes the average, and the second pass the sum of the squared deviations. Include a structure chart.

2.Write a program that reads names and gpa’s from a text file. The file looks like:

James3.9

Margaret 3.5

Charles1.2

Jennifer4.0

Your program sorts the students ascending by gpa, and prints the sorted list including names. To keep the names with the numbers use parallel arrays, one for the names, the other for the numbers. Sort the numbers. Whenever you swap 2 numbers also swap their matching names in the names array. Include a structure chart as in the model lab.

Lab 3 due Feb 32-D arrays

1.Program the “Game of Life”. See p. 440 Programming Project 13. Include a structure chart.

Lab 4 due Feb 10Strings

1.Write a program that reads in a text file and converts it to pig Latin. i.e. if the first letter is a consonant, move it to the end and add “ay” to the end, if it is a vowel add “way” to the end. Here’s an example: “end the war” becomes “endway hetay arway”. Include a structure chart.

2.A file contains a list of names in the form:

Jones, Frederick M

Brennan, Claire

Your program should alphabetize the list. Use the C++ string class. Also, extract names from the input stream with getline().

Lab 5 due Feb 17Vectors

1.Redo Lab 2 Problem 2, only this time use vectors to hold the names and gpa’s instead of arrays. So you will work with 2 vectors, one holding the gpa’s (type double) and the other holding the names (type string).

2.Write a program that reads in an entire text file, word-by-word, storing the words in a vector of string. Then sort the vector alphabetically and print it out. Test on the Gettysburg address.

Lab 6 due Feb 24 Defining a complex number class

1. Define a class for storing and doing arithmetic with complex numbers. Include a UML class diagram for the class. A complex number is often written in the form a + bi, where i 2= -1. a is called the real part, and b the imaginary part. Complex numbers are added, subtracted and multiplied as follows:

(a + bi) + (c + di) = (a + c) + (b + d)i

(a + bi) - (c + di) = (a - c) + (b - d)i

(a + bi) * (c + di) = (ac – bd) + (ad + bc)i

Part a..Define a class named Complex. Each Complex object has two private data field members of type double. Use the names real and imag for these fields.

Define the following public member functions for Complex:

//Constructors

Complex(double r, double i); //Constructs an initialized Complex object.

Complex(); //Constructs a Complex object initialized to 0+0i

//Getters and Setters

double getReal();

void setReal(double r);

double getImag();

void setImag(double i);

//Input and output

void print(ostream& out); //prints a complex number to a stream in the form a+bi

void get(istream& in); //reads in a complex number from a stream in the form a+bi

//Operations

Complex multiply(const Complex & second); //Returns a new Complex object, which is the product of this object with a second object. Does not change this.

Complex plus(const Complex & second); //like multiply only adds

Complex minus(const Complex & second); //subtracts this minus second

Lab 7 due Mar 2Adding operations to a class

Revisit the Complex number class you built in Lab 3 and add on operator overloading as follows:

Operator / Semantics
= / Assigns complex numbers by copying real and imag
== / Returns true if real and imag parts are the same. Since these are floating point numbers, we define same to mean within 0.1 % of each other. i.e. 0.999*real1 < real2 < 1.001 real1.
!= / Opposite of ==
+ / Returns sum
- / Returns difference
* / Returns product
/ / Returns quotient
(a+bi)/(c+di) = (ac+bd)/(c2+d2) + (bc-ad)i/(c2+d2)
ostream::operator< / Inserts a Complex number in the form a+bi into a stream
ostream::operator> / Extracts a Complex number in the form a+bi from a stream

Lab 8 due Mar 16 A class using a dynamic array

p. 687 Programming Project #3 on creating a class that acts like a vector.

Lab 9 due Mar 23Pointers and Linked Lists

1.Write a linked list class named List for storing ints. The linked list is made up of nodes, which are structs with a next field and a data field. The List class should support insertion and removal at the head and insertion at the tail. One way to do this is efficiently is to have the list maintain pointers to both the head and tail. It should also support a print operation to print all the numbers in the order stored.

2.P. 775 #2. In this problem you write a stand-alone merge_lists function which takes as arguments two pointers to ordered lists of int and merges them (in order) into a single list. A pointer to the merged list is returned. The merge is destructive in the sense that the original lists are destroyed and their nodes recycled into the new list.

To test your merge_list function, use the List class you built in Part 1 to construct two lists, each in ascending order. Then merge them into a new list and print out the results.

Lab 10 due Mar 30Recursion

1. Write and test recursive versions of strlen and strcpy.

2.p. 821 Programming project 7 - A recursive sorting function

Lab 11 due Apr 6Inheritance and Polymorphism

1.P. 874 #7 –You will develop skeleton classes for graphics figures using inheritance and virtual functions.

2.(Extra Credit) Modify your classes in Part 1 so that they actually draw things. You can do it crudely in a console application (See P. 855 #8), or more elegantly in a Windows application (See Lab 13).

Lab 12 due Apr 13 Exception Handling

1.Page 909 Programming Project 1. A time manipulation program that throws an exception when an incorrect time value such as 25:05 is entered.

2.(Extra Credit) Page 911 Programming Project 5. A stack that throws an exception on overflow or underflow.

Lab 13 due Apr 19 Building a Windows Program

The goal is to use Microsoft Foundation Classes (MFC) to build a simple windows program. The program allows the user to draw triangles in a window by dragging them out with the mouse. Follow this tutorial.

1. Create a new MFC application named Box using the MFC Application template.

2. When the MFC Application Wizard comes up press the Next button, change to “Single document”, then press Finish, i.e. accept all other defaults. This generates a lot of files.

3. Build your programand test it by pressing the right arrow (debug). It puts up a window on the screen and opens a document inside it. There are menus and a toolbar and some limited functionality, i.e. you can resize the window, minimize it, close it, etc.

4. Switch to Class View. Right-click on CBoxView and press (left-click) properties. This opens up the Properties window.

5. Press the messages tab. Scroll down to WM_LBUTTONDOWN. Press the down arrow button to its right and press the suggested add: OnLButtonDown.

This generates a skeleton function which you will modify later on.

6. In the same way, add OnLButtonUp.

7. Add the following variables to class CBoxView: x1,y1,x2,y2, all of type int.

8. Add the following code after the TODO in the function:

void CBoxView::OnLButtonDown(UINT nFlags, CPoint point)

x1 = point.x;

y1 = point.y

9. Similarly, add to void CBoxView::OnLButtonUp(UINT nFlags, CPoint point)

x2 = point.x;

y2 = point.y

10. Now add additional code to OnLButtonUp(UINT nFlags, CPoint point)to obtain a device context on which to draw, and to draw a rectangle.

CClientDC aDC(this);

aDC.Rectangle(x1,y1,x2,y2);

11. Build and test. You should now be able to drag out rectangles with the mouse.

12.Refer to the tutorial:

to see how to add menu items.

13.Add a menu item allowing the user to choose between drawing a rectangle, an ellipse or a line by setting a mode variable.

Lab 14 due Apr 19 (optional) Enhancing the Windows Program

Implement some of the enhancements suggested at the end of the tutorials in Lab 12.

10/8/20181Prof. M Werner