Table of Contents

vetinnocentΛογισμικό & κατασκευή λογ/κού

7 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

186 εμφανίσεις

Comp
128

Labs


Fall 2012

11/7/2013

1

Prof. M Werner

COMP128 Labs


Fall 201
2


Professor Werner

Table of Contents

COMP128 Labs

................................
................................
................................


Fall 2012 Professor Werner

................................
................................
................................
................................
.........................

1

Lab Submission Rules

................................
................................
................................
..........................

1

Model La
b Submission (as a word doc)

................................
................................
...............................

2

Lab 0.

Simple arithmetic with integers
-
due Sep 7 (no credit for this lab)

................................
.........

5

Lab 1

Using arithmetic operators
-
due Sep 14

................................
................................
..................

6

Lab 2

Numeric calculations including averages and quadratic formula
-
due Sep 21

........................

6

Lab 3 Pay raise, area of a triangle
-
due Sep 28

................................
................................
....................

7

Lab 4 Horoscopes and banners
-
due Oct 5

................................
................................
...........................

7

Lab 5
Approximating e
x
, statistics from a set of numbers
-
due

Oct 12

................................
................

8

Lab 6 Generate a yearly calendar
-
due Oct 19

................................
................................
.....................

8

Lab 7 Program to do arithmetic with fractions
-
due Oct 26

................................
................................
.

9

Lab 8 Streaming numbers from a file
-
due Nov 2

................................
................................
..............

10

Lab 9 Student billing program due Nov 9

................................
................................
..........................

10

Lab 10 Analyzing a text file
-
due Nov 16

................................
................................
..........................

11

Lab 11 Define a Fraction data type (class)
-
due Nov 30

................................
................................
....

11

Lab 12 More analysis of text files
-
due Dec 4

................................
................................
....................

11

Lab 13 Extra Credit


Large integers due Dec 6

................................
................................
.................

12

Lab 14 Extra Credit
-

Strings due Dec 6

................................
................................
............................

12

Lab 15 Extra Credit
-

Reading XML due Dec 6. P.491 #14
................................
.............................

12


L
ab Submission Rules


1.

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


2.

Labs lose
2

point
s

for each week late.


3.

Submit source files (.cpp and .h extensions), design chart and sample test runs.


4.

Source files must have

a heading clearly identifying the lab assignment, your name, the
submission date, and a brief description of the problem including inputs, processing and
outputs.


5.

Labs are
preferably
submitted
through Blackboard. If that fails they may be submitted
b
y
e
-
mail to wernerm@wit.edu. Submit each assignment as a single
word document
. Do
not submit executables or other unreadable files.

See the model problem below.


6.

Labs are to be done individually.


7.

Lab Grades:




Points

Analysis

Identify requirements (usually outputs),
2

Comp
128

Labs


Fall 2012

11/7/2013

2

Prof. M Werner

inputs and processing

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

*

COMP128
-
01

*

Nov 2, 2007

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

*

Problem: Some languages such as German use more capitalization

*

than other languages which share the same alphabet. To check

*

this, a program is needed to read through a text fil
e 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 percenta
ge 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
+CapsCount)

*

Output result as a percent

*

*

See attached structure chart for functional decomposition

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

Comp
128

Labs


Fall 2012

11/7/2013

3

Prof. M Werner

main
isLower
isCap
processFile
In
:
ifstream
c
:
char
c
:
char
Gets file name
Opens file
Prints answer
Scans chars from file
Increments counts
Returns ratio
Returns true if
c is a cap
Returns true if
c is lower
case
Structure Chart for
Lab
8
Problem
1


#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 << "T
he 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))

Comp
128

Labs


Fall 2012

11/7/2013

4

Prof. M Werner




capsCount++;



else

if
(isLower(c))




lowersCount++;



//non
-
letters are ignored


}


return

static_cast
<
double
>(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


COMP128 Lab Assignments


Fall 200
9






M Werner

5

11/07/13






'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 ja
ws 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 ba
ck.

"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 outgra
be.


Lab 0.

Simple arithmetic with integers
-
due Sep
7

(no credit for this lab)


Savitch p. 35

Programming Projects 1


5.

Optional Project 10.


Project 1 is to enter and run the follow
ing program in Visual Studio.


#include <iostream>

using namespace std
;


int main( )

{


int number_of_pods, peas_per_pod, total_peas;



cout << "Press return after entering a number.
\
n";

COMP128 Lab Assignments


Fall 200
9






M Werner

6

11/07/13







cout << "Enter the number of pods:
\
n";


cin >> number_of_pods;


cout << "Enter the number of peas in a pod:
\
n";


cin >>
peas_per_pod;



total_peas = number_of_pods * peas_per_pod;



cout << "If you have ";


cout << number_of_pods;


cout << " pea pods
\
n";


cout << "and ";


cout << peas_per_pod;


cout << " peas in each pod, then
\
n";


cout << "you have
";


cout << total_peas;


cout << " peas in all the pods.
\
n";



return 0;

}


P
roject 5 is to write a program
which reads 2 integers and outputs their sum and product.

Lab 1

Using arithmetic operators
-
due Sep 1
4


1.

Write a program to help carpente
rs. Sometimes measurements are given in terms of
yards, feet and inches. Your program will convert to all inches. When running, it will
prompt the user first for the yards, then the feet, then the inches. Assume all numbers are
whole. Your program will

print out the length in inches.



(1 yard = 3 feet, 1 foot = 12 inches)


2.

Write a program to do the reverse of program 1. It asks the user for a length in inches,
and breaks it up into yards, feet and inches.


3.

(Pro
-
challenge instead of problems 1 and 2) The user types in a length in feet and inches
such as 8’5” and the program types back 101”. Or if the user types 80” the program
types back 6’8”.

Lab 2

Numeric calculations including averages and quadratic formu
la
-
due Sep
2
1


1.

Chapter

2 Programming Projects 10


and 11 on p.105

dealing with various sums and
averages.
(
Submit as one program
)

2.

Write a program to solve a quadratic equation in the form:

COMP128 Lab Assignments


Fall 200
9






M Werner

7

11/07/13








ax
2

+ bx + c = 0



using

the quadratic formula. First fin
d the discrimina
nt:




d = b
2



4ac


If the discriminant is negative, print out a message saying the roots are imaginary and stop.


If the discriminant is zero, print a message saying there is one real root, and then give
the answer,
namely

b/2a.


If the discriminant is positive, print a message saying there are two real roots and then give their
values, namely:



r1 = (
-
b + √d)/(2a)



r2 = (
-
b
-

√d)/(2a)


3. (Pro
-
challenge) Extend

Part 2 so that if the discriminant is negative the program prints out 2
complex roots in the form a+bi.


Lab 3
Pay

raise
, area of a triangle
-
due
Sep 2
8


1.

Chapter

2 Programming Project 3 on p.103

(retroactive pay raise).


2.

Write a program to evaluate
the area of a triangle, given the lengths of its sides.



Use the formula: a = √(s(s
-
a)(s
-
b)(s
-
c)) where s = (a+b+c)/2




Your program first gets the 3 sides from the user. It then checks to make sure it is a
triangle, namely it checks that the sum of an
y 2 sides is larger than the third side.



It then evaluates s and a, and outputs the area a.


3. (Pro
-
challenge) Find the area of a triangle given 2 sides and the included angle)


Lab 4
Horoscopes and banners
-
due Oct

5


1.

Chapter 3

Programming Project
3 on p. 170

(
Horoscopes
)


COMP128 Lab Assignments


Fall 200
9






M Werner

8

11/07/13






2.

Write a program

which prints your name as a banner going from top to bottom. Choose
either your first or last name but it must have at least 5 letters. Write the code to print
each letter in a separate function. If a lette
r appears more than once in your name only
write the function for that letter once. The main() function will simply call the letter
functions one after the other to spell out your name.


For example, the function bannerL to print out the letter L could be

coded as follows:


void bannerL()


{



cout << endl;



cout << “*************
\
n”;



cout << “*
\
n”;



cout << “*
\
n”;



cout << “*
\
n”;



cout << endl;


}

3. (Pro
-
Challenge) Extend part 2 so that instead of always printing '*' the user is asked to enter the
symbol to print. The main() function passes the symbol as a parameter to the functions
which print each letter.

Lab 5
Approximating e
x
, statistics from a

set of numbers
-
due

Oct 1
2


1.

Chapter 3 Programming Project 11

on
p. 17
3

(
Approximating e
x
)


2.

Write a program that allows a user to input a stream of numbers and computes the
ir

average. The user can enter as many numbers as she wants, signaling the e
nd of the
stream by
pressing <CTRL> X
. Use main() to instruct the user, pr
int

the answer and
inquire if the user would like to do it again. Use a function to take in the user inputs,
keep a running total and a count, compute the average and return it.

3.

(optional) Extend part 2 to also compute the standard deviation of the numbers.


Lab 6
Generate a yearly calendar
-
due Oct
19


1.

Write a program to generate a calendar for a year. The program should accept the year
and the day of the week for January 1

of that year (0 = Sunday, 1 = Monday, etc.). The
calendar should be printed in the following form:


January


1


2 3 4 5 6 7 8


9 10 11 12 13 14 15


16 17 18 19 20 21 22

COMP128 Lab Assignments


Fall 200
9






M Werner

9

11/07/13







23 24 25 26 27 28 29


30 31


February


1 2

3 4 5


2. (Pro
-
Challenge) Modify your program so that the user need not type in the day of week for Jan
1. The user simply types in the year. Do a search on the Internet to find out how a
perpetual calendar works.

Lab 7
Program to do arithmetic with

fractions
-
due Oct 2
6


1.

Write a function to compute the greatest common divisor of two integers using Euclid’s
algorithm. Write a driver to test the function.


Euclidean algorithm

from Wikipedia

The
Euclidean algorithm

(also called
Euclid's algorithm
) is an extremely efficient
algorithm

to
determine the
greatest common divisor

(GCD) o
f two
integers
. It is the oldest algorithm known. It
is described in
Euclid
's
Elements
. The algorithm does not require
factoring
.

Given two natural numbers
a

and
b
, first check if
b

is zero. If yes, then the GCD is
a
. If no,
calculate
c
, the remainder after the division of
a

by
b
. Replace
a

with
b
,
b

with
c
, and start the
process again.

For example, the GCD of 1071 and 1029 is computed by this algorithm to be 21 with the
following steps:

a


b


c


1071

1029

42

1029

42

21

42

21

0

21

0


The algorithm can be formulated in the
Python programming language

as follows:


def gcd(a,b):


while b != 0:


c = a%b


a = b


b = c


return abs(a)

COMP128 Lab Assignments


Fall 200
9






M Werner

10

11/07/13







2.

W
rite a program to manipulate fractions. The program allows for the addition,
subtraction, multiplication and division of fractions. You need to submit a structure chart
in addition to the program code and sample runs.

Lab 8
Streaming numbers from a file
-
d
ue Nov
2


1.

Write a program

which reads a stream of numbers from a file, and writes only the
positive ones to a second file. The user enters the names of the input and output files.
Use a function named process

which is passed the two opened streams,
and reads the
numbers one at a time, writing only the positive ones to the output.

2.

Write a program

which reads a stream of numbers from a

file, and prints to the screen

the
highest and lowest numbers found.

Lab 9
Student billing program
due Nov
9


Write

a student billing program. Student information is kept in an input file. The file has 3
fields, last name, first name, hours. Here is an example:



Smith Alice 15 Jones Fred 10 Wang Phil 20



The billing system is as follows:




A regular load is from 12
.0 to 18.0 hours. The bill is $7,000.



An overload is more than 18.0 hours. The student is billed $7,000 for a regular load plus
$400 for each excess hour over 18.0.



An underload is less than 12 hours. The student is billed $450 per hour.


Output is to
be written to an output file. It will be in the form of a report with fields for:




last name, first name Example: Smith, Alice



hours



regular hours



regular bill



overload hours



overload bill



underload hours



underload bill



total bill


The report should be pr
operly formatted. Plan it on a sheet of paper first to get a good layout.
The paper has a width of 80 columns. Hours should always be printed with one decimal place,
COMP128 Lab Assignments


Fall 200
9






M Werner

11

11/07/13






and dollar amounts with two. Columns should line up. Note: To make this work when pr
inting,
you need to use a fixed width font such as Courier.

Lab 10
Analyzing a text file
-
due Nov 1
6


1.

Write a program that analyzes a text file by counting the number of times each of the 26
letters in the alphabet is used. How many a’s, how many b’s,
etc. Count capital and
lower case versions of the same letter as one.


2.

Write a function

which is passed an array of int and its size, and prints out only the
numbers that are above average.


3.

Extra Credit (2 pts)


Repeat Part 1, but print out the le
tter counts in order of decreasing
frequency, i.e. E 20, T 18, S 15, etc.

Lab 11
Define a Fraction data type (class)
-
due
Nov 30


1.

Write a class definition for a Fraction class. Its member fields are num and den, both of
type int. The constructor buil
ds the default fraction 1/1. It has the following operations:


void plus
Equals
(Fraction second); //Adds the second fraction to this fraction

like the operator +=

void minus
Equals
(Fraction second); //Subtracts the second fraction from this fraction

void
times
Equals
(Fraction second); //Divides this fraction by the second fraction

void divides
Equals
(Fraction second); // Divides this fraction by the second fraction

void reduce(); // Reduces this fraction to lowest terms

double todecimal(); //returns the d
ecimal value of this fraction

void scan(istream&); //scans a fraction written with a slash as in ¾

void print(ostream&); //prints a fraction using a slash

Fraction(); //constructs a default fraction with denominator 1, numerator 0

Fraction(int n, int d);
//constructs a fraction given value for num and den


2.

Write a menu
-
driven driver program designed to allow thorough testing of your Fraction
class.

Lab 12
More analysis of text files
-
due Dec
4



1.

Write a program

which scans a file and counts the numb
er of characters, the number of
lines, and the number of alphabetic characters in the file. Have main() open the file and
pass the file pointer to a function named count. Count passes back the number of
characters and the number of alphabetic characters.

main() prints the answers and closes
the file.


COMP128 Lab Assignments


Fall 200
9






M Werner

12

11/07/13






2.

Write a function named is_vowel, which is passed a char, and returns 1 if it is a vowel, 0,
otherwise. Write a main() to test it. The user types some input, ends by pressing <ctrl> z
on its own line, a
nd the program prints out the numbers of vowels and consonants typed.


Lab 13

Extra Credit


Large integers

due Dec
6


Chapter 7

Pro
gramming Project 7 on p. 433
. It involves storing and adding large integers using
arrays of int.


Lab 14

Extra Credit
-

Stri
ngs

due Dec
6


1.

p. 488

#6 (replace digits by x’s)


2.

p. 489

#11 (converts words to pig latin)


Lab 15

Extra Credit
-

Reading XML

due Dec 6
. P.491 #14