28
CSC134 Lab Descriptions Lab 1 (Chapter 2 Material) This lab requires simple calculations and the use of simple output statements. Remember the characteristics of integer arithmetic. Problem statement The Ringy Manufacturing Company makes a common household item called a doflingy. The Ringy Doflingy shipping clerk is faced with the following problem: Doflingies are very delicate and must be shipped in special, very expensive, containers. These containers are available in 5 sizes: huge, large, medium, small, and single which can hold, respectively, 50, 20, 10, 5 and 1 doflingies. Write a program that assumes a number of doflingies to be shipped and displays the number of huge, large, medium, small, and single containers needed to send the shipment in the minimum number of containers and with the minimum amount of wasted container space. The number of doflingies to be shipped should be a variable called ‘number’. The output should look similar to the following, which is the solution to the problem when the number of doflingies to be shipped is 137. Test your program by using various values for ‘number’. Container Size Number Required ----------------- --------------------- Huge 2 Large 1 Medium 1 Small 1 Single 2 document.docx 1 1/18/22

CSC134LabExercises_v09

  • Upload
    huseyi

  • View
    461

  • Download
    9

Embed Size (px)

Citation preview

Page 1: CSC134LabExercises_v09

CSC134 Lab Descriptions

Lab 1 (Chapter 2 Material)This lab requires simple calculations and the use of simple output statements. Remember the characteristics of integer arithmetic.

Problem statementThe Ringy Manufacturing Company makes a common household item called a doflingy. The Ringy Doflingy shipping clerk is faced with the following problem: Doflingies are very delicate and must be shipped in special, very expensive, containers. These containers are available in 5 sizes: huge, large, medium, small, and single which can hold, respectively, 50, 20, 10, 5 and 1 doflingies. Write a program that assumes a number of doflingies to be shipped and displays the number of huge, large, medium, small, and single containers needed to send the shipment in the minimum number of containers and with the minimum amount of wasted container space. The number of doflingies to be shipped should be a variable called ‘number’. The output should look similar to the following, which is the solution to the problem when the number of doflingies to be shipped is 137. Test your program by using various values for ‘number’.

Container Size Number Required ----------------- ---------------------

Huge 2Large 1Medium 1 Small 1

Single 2

document.docx 14/11/23

Page 2: CSC134LabExercises_v09

Lab 2 ( Chapter 2 Material ) This lab requires the application of simple arithmetic statements and simple output statements.

Problem statementWrite a program that estimates the temperature in a freezer ( in degrees Celsius ) at some time ( t) after a power failure. The user should be prompted to enter the elapsed time since the power failure ( in hours and minutes ). The temperature ( T ) is modeled by the formula

T = 4t2/(t + 2 ) – 20 ( t is assumed to be given in units of hours )

The model assumes that the temperature in the freezer at the time the power is turned off is -20 degrees Celsius. That can be verified by setting t = 0 in the formula.

Declare as integers variables for hours and minutes. Initialize these variables in your code, and convert them to a single number, hours. For example, if the user enters 1 hour and 45 minutes, your program needs to convert those numbers to 2.75 hours. Be sure your program displays the units ( degrees Celsius ) with the answer.

As one test, try your program with hours = 6 and minutes = 31. The resulting temperature should be very, very close to ( but probably not equal to ) 0 degrees C. A basic test would be to set hours = minutes = 0, in which case the temperature should be 20 degrees C.

Of course, your program should work with any data supplied in your program, not just the above test data.

document.docx 24/11/23

Page 3: CSC134LabExercises_v09

Lab 3 ( Chapter 3 Material ) This lab is mainly an output-formatting exercise. It does require that you know how to develop the product of two 3-digit integers, without using a calculator.

Problem statementWrite a program that multiplies two 3-digit positive integers (000 – 999) and prints their product in the format below. Your program should ask the user to type the two numbers, and then read them in. Your program should still format the output properly even if the high-order digits of one or both of the numbers are zeros (i.e., 027 or 003 or 000). As an example, the product of 433 and 456 should produce the following output. Notice that the alignment should be the same as you would get if you multiplied the numbers using a pencil and paper (1’s column, 10’s column, 100’s column, etc.).

456 x 433 --------- 1368 13680 182400 --------- 197448

document.docx 34/11/23

Page 4: CSC134LabExercises_v09

Lab 4 ( Chapter 3 Material ) This lab may be a little more complicated, unless you use the hint described below.

Problem statementAngles are often measured in degrees (), minutes (‘), and seconds (“). There are 360 degrees in a circle, 60 minutes in one degree, and 60 seconds in one minute. Write a program that reads two angles expressed in degrees, minutes, and seconds from a file, and then calculates and prints their sum. The number of minutes in your answer should be no greater than 59, and the number of seconds in your answer should be no greater than 59. The number of degrees in your answer should be no greater than 360. Why do you suppose that’s the case?

Hint: This problem can be messy, unless you tackle it in a methodical way. A suggested approach is to first convert both angles to seconds, before you add them. After you do the addition, your result will be in seconds. You can then convert the resulting seconds to degrees, minutes, and seconds, and display your answer in that form.

Since it may be difficult to print the special character representing degrees, use the characters d, m, and s to represent degrees, minutes, and seconds, respectively. For example, 15034’21” can be represented as 150d 34m 21s. Your answer should be presented in the following format:

7d 14m 55s + 5d 24m 55s = 12d 39m 50s

You may obtain a sample input file from Blackboard. Test your program with various pairs of angles (i.e., multiple input files).

document.docx 44/11/23

Page 5: CSC134LabExercises_v09

Lab 5 (Chapter 3 Material )When you move toward a stationary light source, the wavelength of the light emitted by the source decreases. In fact, it decreases according to the following formula:

w1 = w0*( 1 - v/c0 )

where w0 is the wavelength of the color emitted by the light source ( that is, as seen by a non-moving observer ), w1 is the wavelength of the color of the emitted light as perceived by you while you’re moving toward the source, v is the speed at which you’re moving toward the source ( assume speed is expressed as miles per hour ), and c0 is the speed of light ( assume light travels 669,600,000 miles per hour ). This phenomenon is known as ‘Doppler shift’, in honor of the Austrian mathematician Johan Christian Doppler ( 1803 – 1853 ).

The wavelength of green light is shorter than that of red light. This means that as you approach a red light, the color of the light shifts toward the green spectrum.

Now suppose a police officer stops you for running a red light. Clever person that you undoubtedly are, you argue that as you approached the light, the Doppler shift caused the red light to look green to you. Compassionate person that the officer is, he agrees to write you a ticket for speeding, instead of writing one for running the light. In the particular town in which you committed the infraction, the fine for running a red light is $100, and the fine for speeding is $1 for every mile per hour you travel over the speed limit. The speed limit is 25 miles per hour. Write a program that uses the above formula to calculate and display your speeding fine. You’ll need to solve the equation above for v, your speed as you approached the traffic signal. Use .533 microns for the wavelength of green light and .674 microns for the wavelength of red light. Display your fine as currency ( dollars and cents ).

If you want to know more about wavelengths of light and their relationships to human vision, see the table and brief discussion in lab 7 below.

document.docx 54/11/23

Page 6: CSC134LabExercises_v09

Lab 6 ( Chapter 4 Material ) This is a “gas meter” problem. The gas meters in the problem show integer values only in the range of 0 to 9999 cubic meters. When the meter reaches 9999, it then “starts over” with the value 0000. This is a common consideration that has to be handled anytime we measure things, since all measurement devices place a limit on the largest number the device can record.

Problem statementSuppose charges by a gas company are based on the user’s consumption, according to the following table:

Gas Used Rate

First 70 cubic meters $5.00 minimum costNext 100 cubic meters 5.0 cents per cubic meterNext 230 cubic meters 2.5 cents per cubic meterAbove 400 cubic meters 1.5 cents per cubic meter

Ensure that you charge only once at the correct rate for each cubic meter of gas.

Write a program that computes the charges for a given amount of gas usage. Have the program read in the meter reading for the previous month and the reading for the current month, each an integer with up to 4 digits, and each reading representing cubic meters. The program should then calculate and display the amount of payment due from the customer. NOTE: The reading for the current month could be less than the reading for the previous month, because after the reading reaches 9999, it starts over with the value 0000. For example, if the previous month’s reading was 9875 and the current month’s reading was 0078, the customer actually used 203 cubic meters during the current month. This can probably be calculated in a variety of ways. A straightforward way, of course, is to subtract 9875 from 10000 and add 78 to the result. This approach will be satisfactory for our purposes, when the current reading is less than the previous reading, i.e., in that case uses the following formula:

Gas used = 10000 - previous reading + current reading

If the current reading is greater than the previous reading, then of course we just have to subtract the previous reading from the current reading.

Display your result in the way illustrated by the following example:

Last Month’s Reading: 9875 cubic meters This Month’s reading: 0078 cubic meters Gas Used: 203 cubic meters Total Charges: $10.83

document.docx 64/11/23

Page 7: CSC134LabExercises_v09

Lab 7 ( Chapter 4 Material ) Problem StatementWavelengths of visible light are approximately in the range of .4 to .7 microns. The table below shows the relationship between color and wavelength. Write a program that asks the user to supply a wavelength. The program should use that input and the tabular values to display the color (as text) associated with the input wavelength. Any input wavelength less than .4 microns or greater than .7 microns should return an error message stating that the input wavelength is outside the range of visible light.

Wavelength range(microns) color .400 to less than .424 violet .424 to less than .491 blue .491 to less than .575 green .575 to less than .585 yellow .585 to less than .647 orange .647 to less than .700 red

document.docx 74/11/23

Page 8: CSC134LabExercises_v09

Lab 8 ( Chapter 5 Material ) The value of the mathematical constant pi can be approximated by the following series:

pi = sqrt( 6*(1 + 1/4 + 1/9 + 1/16 + 1/25 +.......) )

There are an infinite number of terms in the series, so you can’t compute pi exactly; But you can approximate it by using as many terms as you need and ignoring the rest of them. Notice that the terms do get smaller and smaller.Note that there’s a pattern to the terms in parentheses, and by looking at the pattern you can accurately guess what the next few terms are. For example, guess what the next term is. Hint: It’s 1/36. In general, term n is 1/n2.

Problem StatementYour problem for this lab is to write a program that approximates pi using the above series. Allow the user to specify the number, n, of terms to be used. Try your program with n = 100, then 1000, then 100000, etc. all the way up to and including n = 1 billion.Don’t worry, your program ( if properly written ) will be fast, and n = 1 billion should take only a few seconds on a reasonably fast PC.

Note how the approximation becomes better and better as you increase the number of terms. Make your integer data types ‘long long’ and your floating point data types ‘long double’. In our compiler a long long integer is 8 bytes and a long double floating point number is 12 bytes. You can verify that by writing a little program that prints sizeof(long long ) and sizeof(long double).We’ll discuss the reason for using those data types in class. For comparison purposes, the correct value of pi to 15 decimal places is 3.141592653589793. You won’t get that kind of accuracy with your program, but you should get about 7 or 8 decimal place accuracy with n = 1 billion.

DiscussionIt’s said that Sir Isaac Newton once used this formula to estimate the value of pi. Obviously, if he did use it, he didn’t get the kind of precision that you can get with your program, because he had to do the calculations by hand; So n = 1 billion was entirely out of the question for him. This is an example of what we discussed before: With the power of a computer, you can construct problem solutions that were completely beyond the reach of even the greatest scientists and mathematicians the world has produced.

document.docx 84/11/23

Page 9: CSC134LabExercises_v09

sum of rectangle areas gives approximate area of the shape

x- axis

height (y-value) of a given rectangle depends on where the rectangle intersects the circle

x-value

y- axis

Lab 9 ( Chapter 5 Material )

In manufacturing certain products it may be required to determine the area of an irregular shape. If a formula does not exist to calculate the area exactly, a method may be used to calculate an approximate value for the area. Approximate methods can be accurate even though they are not exact. In this lab you use an approximate method for calculating the area of a circle. A circle is chosen so you can compare the exact area with the approximate area your program calculates.

BACKGROUND INFORMATION

In principle, the approximate area of a shape may be calculated by dividing the shape into a number of imaginary rectangles, calculating the area of each rectangle, and summing the areas of the rectangles.

Figure 1

APPLICATION TO A CIRCLE

For a circle, you can simplify things if you work with only the first quadrant of the circle. The

area of the first quadrant, multiplied by 4, gives the total area of the circle. Suppose you divide

the quadrant into a number of rectangles, each having the same width along the x-axis. The

height, y, of a given rectangle depends on where the rectangle intersects the circle.

Figure 2The y-value at the intersection depends on the x-value (Fig 2).

document.docx 94/11/23

Page 10: CSC134LabExercises_v09

y = radius2 – x2

y = R2 – W2

W * R2 – W2

x axis

R

W

y

W

W * R2 – (2*W)2

W * R2 – (3*W)2

rectangle area = W * R2 – (i*W)2

For a circle centered at the origin with radius R, we have

y2 = radius2 – x2 or

Using this formula, we can calculate the value of y for any given value of x.

Now, suppose the width of a rectangle is W and the radius is R (Figure 3). The area of the first rectangle is simply (width * height), that is, (W * y). But since

we can substitute for y, giving the area of the first rectangle as

Figure 3

The area of the second rectangle is given by

The area of a third rectangle is given by

In general, the area of any given rectangle in the quadrant is

where i is the ith rectangle. The accuracy with which the total area is calculated depends on the number of rectangles. For a

circle of given radius, the more rectangles you use, the smaller the width each will have, and the

more accurate the calculation will be because the rectangles will fit closer to the shape. The

document.docx 104/11/23

Page 11: CSC134LabExercises_v09

results of this lab demonstrate how the accuracy of the calculated area of a circle depends on the

number of rectangles.

Program Specifications1. Your program must allow the user to investigate an indefinite number of circles without

having to restart each time. Use a loop in main( ) to do this.2. The user is prompted to enter the radius. Provide a means for handling invalid input.3. Compute the approximate area of a circle, centered at the origin, using the method described

above and the running sum technique.4. For this lab it is better to use the pow( ) function to compute the square of a value instead of

multiplying the value by itself.5. Five calculations are done

calculation 1:The exact area, using 3.14159265358979 for the value of . (Use a defined constant and include all digits for accuracy)

calculation 2:Approximate area, using 100 rectangles

calculation 3:Approximate area, using 1000 rectangles

calculation 4:Approximate area, using 10000 rectangles

calculation 5:Approximate area, using 100000 rectangles

6. All results are to be displayed to 4 decimal places.7. Display the user-supplied radius and results of all four calculations, using the format shown

below. You will see how the number of rectangles you use affects the accuracy of the calculated area.

Circle radius = x.xxxx

Exact area = x.xxxxApproximate area using 100 rectangles = x.xxxxDifference from the exact area: x.xxxx

Approximate area using 1000 rectangles = x.xxxxDifference from the exact area: x.xxxx

Approximate area using 10000 rectangles = x.xxxxDifference from the exact area: x.xxxx

Approximate area using 100000 rectangles = x.xxxxDifference from the exact area: x.xxxx

document.docx 114/11/23

Page 12: CSC134LabExercises_v09

An Interesting Historical Note

In 1897, the Indiana State House of Representatives passed a bill (House Bill 246) supposedly setting the value of pi. The bill was defeated in the Senate, despite support from the State Superintendent of Education. It was written by Edward J. Goodwin (who was offering his mathematical results to the State of Indiana, "free of charge"), and introduced by Representative Taylor I. Record. According to David Singmaster, in the Mathematical Intelligencer, the bill was actually ambiguous, and seemed to say that pi is equal to the following values:

43.3333 . . .3.23.5555583.2324883.265306

It also implied that the square root of 2 is 10/7. The bill can be found in several sources, including the Indiana State Library. See Indiana bill sets the value of pi to 3.

Another way to get a better estimate of pi( pseudocode):

Jonathan and Peter Borwein (at one time holders of the world record for most digits of pi) give the following computer algorithms for calculating pi (which I modified slightly). In both methods, a approaches 1/pi (* is multiplication, ^2 is squared, sqr(2) is the square root of 2):

Method A:

start: n=0; y=1/sqr(2); a=1/2;repeat: n=n+1; y=(1-sqr(1-y^2))/(1+sqr(1-y^2)); a=(a*(1+y)^2)-y*2^(n+1);

Method B (really efficient):

start: n=0; y=sqr(2)-1; a=6-4*sqr(2);repeat: {n=n+1; y=(1-sqr(sqr(1-y^4)))/(1+sqr(sqr(1-y^4)));a=(a*(1+y)^4)-y*(1+y+y^2)*2^(2*n+3)};

document.docx 124/11/23

Page 13: CSC134LabExercises_v09

Lab 10 ( Chapter 6 Material ) The area of an arbitrary triangle can be calculated using the following formula:

area = sqrt( s*(s-a)*(s-b)*(s-c) )

where a, b, and c are the lengths of the sides and s is the semiperimeter:

s = ( a + b + c )/2

and, of course, sqrt() is the square root function accessible through the cmath header file.

Problem StatementWrite a function, call it ‘calc’ that has a ‘void’ return type and 5 parameters: a, b, c, &s, and &area. Your program should calculate the perimeter and area in ‘calc’ and store them in the reference parameters s and area.

Write a main function that prompts the user for a, b, and c. Your main() function should call ‘calc’ with the appropriate arguments. Do not use global variables.

NOTE: Your program should be robust, i.e., it should check to see that the values of a, b, and c entered by the user can, in fact, represent the sides of a triangle (see lab 6 discussion). Prior to calling ‘calc’, your main function should check to see that this condition is satisfied and display an error message if it is not satisfied.

Your output should be from the main function and should be in a form similar to that shown below, for a = 2, b = 2, c = 2:

For a triangle of sides 2, 2, and 2, the perimeter is 6.000 the area is 1.732

The area and perimeter should be given to a precision of 3 decimal places.

document.docx 134/11/23

Page 14: CSC134LabExercises_v09

Lab 11 ( Chapter 6 material )Problem StatementWhen an object moves through the atmosphere it must overcome a force called aerodynamic drag, which exerts itself against the object. The drag force is given bythe following equation:

F = .5*Cd*A*ρ*V2

where F is the force ( newtons ) on the object that acts to retard its motion, Cd is an experimentally-determined number called the drag coefficient, A is the projected area of the object perpendicular to the direction of motion ( square meters ), ρ is the density of the atmosphere through which the object moves (kilograms per cubic meter ), and V is the object’s speed ( meters per second ). For a reasonably streamlined object, the value of Cd is somewhere around .2, sometimes smaller. For a very un-streamlined object, A value of Cd somewhere near .8 to 1 is more likely. Assume ρ = 1.23 kilograms per cubic meter. Write a program that allows the user to input A and Cd and calls a function to compute and return the corresponding value of F to your main function. The main function should display the returned result. Your main function should call the drag force function repeatedly and display each result for values of V between 5 and 50 meters per second, in 5 meter increments.

“How do I verify that my program is producing correct results?”, you might be tempted to ask. Here’s a standard method: use some test values for Cd, A, and V in your program. Run the program with those values and note the results. Then fire up your hand calculator and calculate F, using the above formula and the same test values you used in your program. If the results match, that’s a pretty good indication that your program calculates correctly. If the results don’t match, there’s something wrong somewhere, and you’ll need to find and fix the problem. It’s called hand verification, and somebody has to do it. Welcome to the painful side of programming.

DiscussionIf you remember back to your high school physics classes, you probably always made your calculations by assuming you can neglect the effect of the atmosphere on a moving object. The above formula enables you to include that effect and it is very necessary for accurate modeling of an object’s motion. Strictly speaking, Cd is called the pressure drag coefficient. There is also a skin friction drag and a base drag coefficient, but the effects of those drag forces are typically much less than the pressure drag force.

document.docx 144/11/23

Page 15: CSC134LabExercises_v09

Lab 12 ( Chapter 7 Material )

Problem StatementWrite a program to assign passengers seats in a small airplane. The seat numbering is given below:

Row Left Side Right Side

1 A B C D2 A B C D3 A B C D4 A B C D5 A B C D6 A B C D7 A B C D

For output, the program should display the seat pattern, with an ‘X’ marking the seats already assigned, as in the example below:

Row Left Side Right Side

1 X B C D2 A B X D3 A B C X4 A X C D5 A B C D6 X B X X7 A B C D

After displaying the current seating assignment, the program should prompt for the seat desired, and the user should type in the desired seat. The seating assignment table should then be updated and re-displayed. This should be continued until all seats are filled or until the user signals that the program should end. The details for doing this are left for you to decide. Since this is Chapter 7 material, it’s clear that arrays should be used.

If the user types in a seat that is already assigned, a message stating that the seat is occupied should be displayed, and the program should ask for another choice. CAUTION: What happens if your user enters a subscript that is out-of-range for your seat array? Can you afford to allow that to happen?

document.docx 154/11/23

Page 16: CSC134LabExercises_v09

Lab 13 ( Chapter 7 Material )As you no doubt know, computers are great for playing games. In this lab, we’ll write a program that plays a simple game of tic-tac-toe, a game you’ve probably played since childhood. We’ll write the program in such a way that it will allow one person to play against another. A more difficult program would allow a person to play against the computer, and the program would endow the computer with some kind of “intelligent” decision-making ability at each move. A REALLY sophisticated program could actually “learn” to make good strategic plays by evaluating the result of each move, using the initial board configuration and the configuration after the move has been made. That’s one kind of thing studied in the area of “artificial intelligence”. This kind of approach has been taken to construct, for example, expert chess-playing programs. In this class, we’ll stick to playing tic-tac-toe, and just relegate the computer to the task of recording and reporting the progress of the game.

Problem StatementWe need a program that will allow two players to play a game of tic-tac-toe. The program should ask for moves alternately from player X and player O. The program should display the game position as follows:

1 2 34 5 67 8 9

The players should enter their moves by entering one of the position numbers 1 through 9. The program should convert the specified move to one of the positions in the two-dimensional array shown above. The program should also validate the player’s desired move, to make sure the position hasn’t been previously occupied. After each move, the program should display the current configuration of the. A sample configuration is shown below, after 4 moves have been made. The program should check after each move to determine whether a player has won and also allow for a user to terminate the game, if he wishes to do so, when it is his turn to play.

X X O4 5 6O 8 9

CAUTION: What happens if your user enters a subscript that is out-of-range for your game array? Can you afford to allow that to happen?

document.docx 164/11/23

Page 17: CSC134LabExercises_v09

Lab 14 ( Chapter 8 Material )Sorting the elements of an array is a task that’s often required. It’s also often necessary to sort on more than one field. For example, a two-dimensional table that contains the year, month, and date may have to be sorted on all of those fields. We’d usually first sort on the year, then within each year, we’d sort on the month, and finally, for each month we’d sort on the date. Note that in multi-field sorting, one has to pay careful attention to which field is sorted first, which is sorted second, etc. For example, in the preceding situation we wouldn’t usually sort first on month, then on year, then on date.

Problem StatementFor this lab, we’ll use the two-dimensional table; call it ‘employees’, shown below. Read these data into your program from the file provided on Blackboard. Don’t include the headings in your array, of course, they’re there for explanatory purposes.

Department Employee Number Monthly Pay2 5 10505 17 12003 12 12252 23 13003 6 11403 3 11102 4 14202 1 13605 14 12255 11 13805 10 14102 2 15653 8 14455 7 13873 9 11282 16 1488

For this lab, your job will be to write a program that sorts a table like the above on the two fields ‘Department’ and ‘Employee Number’. Sort first on department; then, within each department sort on employee number. Use a selection sort only. Write a function called ‘sortem()’ that does the actual sorting. Declare the ‘employees’ table (array) in your main() function. Call sortem() from the main() function, and pass the ‘employees’ table to sortem(), which should sort the table and return control to main(). Your main() function should display the resulting table after the sorting is done. It should be displayed in a format similar to that above. Do not use any other arrays to help you sort, use only employees, i.e., don’t copy data from the employees array to an auxiliary array to facilitate sorting. Your program may be tested on a different data set from that above, so be sure your program is independent of the specific numbers given above. The data shown is just for your own testing purposes. To ensure that your program works with other data, you may want to test it on some data you make up. Assume in your program that the maximum size that will be needed for the employees table is 100-by-3, i.e., ‘employees’ should be declared as shown below:

document.docx 174/11/23

Page 18: CSC134LabExercises_v09

short employees[100][3];

Tall employees may be included later :>)

document.docx 184/11/23