Vous êtes sur la page 1sur 34

GNG 1101

Fundamentals of Engineering Computation


Laboratory Manual
2003 Edition

D. T. Gibbons

1. Computer Laboratories, Software Reports and Getting Started


Laboratory Schedule and Teaching Assistants.
The laboratory schedule has been given to you with the course outline. Please refer to
this schedule to find out which lab exercise you must do on a given week. The laboratory
time will be spent working on the programming assignment that is due on the following
laboratory session. During this time, your Teaching Assistants (TAs) will be available to
answer your questions. If you do not complete the assignment during the allocated time
period, you will be expected to complete it on your own time. If you have access to a C
compiler, you may finish the work at home. Alternatively, you may work on the
assignment in the faculty computer laboratories.
The three hour lab period will be supervised by the same TAs for the whole term. Please
ensure that you have the name of your TA, email address, office hours and office number.
Your TAs are responsible for marking your laboratory assignments based on a consistent
and fixed marking scheme. Please see your TA(s) for all questions regarding your
laboratory marks.
Software Reports and Our Problem Solving Strategy
The reports must be sent electronically as an attachment to your TA using the mailing
utility to be found in the course web site (explanations given below). Your lab report
must be received by the beginning of the next lab session. Late laboratory reports will
NOT be accepted and hence will count as zero. If you must hand in a laboratory
assignment late due to exceptional circumstances such as illness, you must see the
professor. Plagiarized work will also be given a mark of zero and will be given to the
professor who will pass it on to the Faculty of Engineering Deans Office or action under
the rules on Academic Fraud (Engineering Calendar page 21 or
http://www.uottawa.ca/academic/info/regist/crs/home_5_ENG.htm and check
http://www.uottawa.ca/plagiarism.pdf ).
Your completed assignment will consist of a standard typewritten software report along
with your program source code and relevant test cases. The report must comply with the
standard format, which is outlined in the following example. The problem solving
methodology to be followed for all laboratory assignments is also described in this
example.

GNG1101

Software Report Format - An Example


The methodology that will be followed for problem solving has five steps. These five
sections must be identified clearly in the software report.
Step 1. Problem identification and statement.
Step 2. Gathering of information and input/output description.
Step 3. Hand solved examples and algorithm selection or design.
Step 4. Implementation.
Step 5. Software testing and verification.
In addition, a users guide must be provided at the end of the report. The following
example illustrates the application of our problem-solving methodology. The text
highlighted in italics and the figures are in fact the contents of the lab report that would
be handed-in for this example problem.
STEP 1: Problem Identification and Statement
The first step is to give a clear and concise problem statement. This should help to avoid
any misunderstandings. For this particular example, the problem statement will be:
Compute the distance between two points on a plane.
STEP 2: Gathering of Information and Input and Output Description
The second step is to gather and describe the information that is required to solve the
problem and then to identify the inputs and outputs.
We wish to compute the distance between the two points. We can use the
Pythagorean theorem to determine the hypotenuse of the associated right angle
triangle, as illustrated below:

GNG1101

P2(x2,y2)

hypothenuse
side 2

x
P1(x1,y1
)

side 1
Hypothenuse =
=

(side 1)2 + (side 2)2


(x2 x1 )2 + ( y 2 y1 )2

Figure 1.1: Gathering of the required information.


For many problems, an input/output (I/O) diagram is useful. In such a diagram, the
computer program is simply represented by a black box since the steps to solve the
problem have not been determined. The inputs flow into the box, and the outputs emerge
from it.
The I/O diagram for this problem is illustrated below.

Point
#1

Distance
between
the two points.

Point
#2

Figure 1.2: I/O Diagram.


In your report you can replace this diagram by text to ease the difficulties of drawing the
diagrams electronically, such as:
Inputs:
Point#1 and Point#2
Output:
Distance between the two points.
GNG1101

STEP 3: Hand solved examples and algorithm selection or design


The third step is quite important, because this is when you understand what needs to be
done to solve the problem and how to create the program. It is more than understanding
the problem, it is having clues on how it should be solved, it is understanding the mental
process that you use to solve it. When possible, trying to solve the problem by hand
using a simple set of data is the best way to figure out a solution, and to set expectations
on the behavior of the program. We need to understand what we want the program to do
if we are to test it at a later stage. This is a very important step and should not be
omitted. If you are unable to solve the problem by hand for a simple set of data then you
are definitely not ready to code the solution as a computer algorithm. It is in this step
where you mentally attack and solve the actual problem. If you cannot solve the
problem, you should reread the statement or perhaps look up reference material (library,
Web) or contact the TA or professor. For our problem, a simple hand solved example
could be:
Let the points P1 and P2 lie on the following coordinates:
P1 = (-1,-3), P2 = (4,6)
We wish to compute the distance between the two points. We can use the
Pythagorean theorem to determine the hypotenuse of the associated right angle
triangle, as illustrated below:
y

P2(4,6)

hypothenuse
side 2

x
P1(-1,3)

side 1

(side 1)2 + (side 2)2


(x2 x1 )2 + ( y2 y1 )2

(4 (1) )2 + (6 (3) )2

Hypothenuse =

= 106 10.3
Figure 1.3: A hand solved example.

GNG1101

Once you are able to solve the problem for a simple set of data, you are then ready to
develop an algorithm (a step-by-step outline) of the problem solution to be coded in a
high-level programming language. In the algorithm, you are summarizing every logical
step that will be required to solve the problem, based on your hand calculation
experience. For our problem, the algorithm can be expressed as:
Begin:
(a) Define the coordinates of the two points.
(b) Determine the length of the two sides of the right triangle generated by
these two points.
(c) Compute the distance between the two points (which is the hypotenuse
of the right triangle).
(d) Print the distance between the two points.
End.
STEP 4: Implementation.
It is at this point that we proceed with the implementation of the algorithm described
above using a high-level programming language; in our case C.
The C program developed to solve our problem is listed below.
/*--------------------------------------------------*/
/* Name: yournamehere, Student Number: 0000001
*/
/* Date: Sept 01, 2003.
*/
/* Program: distance.c
*/
/* Description: This program computes the distance */
/*
between two points.
*/
/*--------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
/* Declare and initialize the variables */
double x1 = -1, y1 = -3, x2 = 4, y2 = 6,
side_1, side_2, hypothenuse;
/* Compute the sides of a right triangle */
side_1 = x2 - x1;
side_2 = y2 - y1;
/* Compute the distance between the two points. */
hypothenuse = sqrt(side_1*side_1 + side_2*side_2);
/* Print the distance */
printf("The distance between the two points is %5.2f \n",
hypothenuse);
system("PAUSE");
return 0;

}
/*--------------------------End---------------------*/

GNG1101

Note that the implementation maps directly to the algorithm designed. Do not worry if
you do not understand at this point all of the C program statements. You will gain
understanding and confidence as the semester progresses. It is good software
engineering practice to add sufficient comments so that others may clearly understand the
code. A properly commented and documented program is essential. Marks will be
deducted if meaningful comments are not included throughout the code. Also note that
meaningful variable names improves the readability of the program, as well as the use of
constants. A consistent style, with regular indentations for subsections (loops, decisions)
of code is also essential for readability. In our example, a header section identifies the
programmer, the date programmed, he name of the source code file and gives a
description of the task performed by the program.
Please ensure that the listing introduced at this point in your report appears correctly.
This is best achieved by copying the program listing from the programming environment
and then pasting it into the report using the Courier or Courier New fonts.
STEP 5: Tests and Verification (and Debugging)
Once the source code is compiled and linked without error, it must be tested to ensure
that it is correctly computing the desired solution. An obvious test would be to verify
that the program generates the same solution for the simple data set used for your hand
calculation. If there is a discrepancy between the two, then both the program and the
hand calculation should be re-examined for errors. When both solutions are in
agreement, the computer program should be tested with additional sets of data to ensure
that the solution works for other valid input sets. Based on these tests, you should be
able to conclude whether your program executes correctly or not. For our example, it
would be wise to verify the program for input coordinates that are a mixture of both
positive and negative values.
For the hand calculation data of P1 = (-1,-3) and P2 = (4,6), the output is:
The distance between the points is 10.30

which is in agreement with the hand calculation solution.


For P1 = (-5,-5) and P2 = (-5,-10), the output is:

The distance between the points is 5.00

which is the correct distance for this data set.


etc... (other tests)
We can therefore conclude that the program is functioning correctly.

GNG1101

When a program is supposed to perform a certain operation for a range of data, it is very
important to test the performance of the program at the limits of the range. Limits just
tend to be problematic cases that programmers often forget about, but forgetting about a
limit might change your results, and also you can never know what the user will do.
If you find flaws in your system, cases for which the program is not robust (eg. it fails for
a certain type of entry, etc), you should advise the possible user in making this clear in
your users manual (see further section on users guide).
You must include in your report a copy of the console window displaying the output of
your program for each test case. The procedure for copying your console window into
your lab report is given in the next section. For this example, the console windows are:

Fig 1.4 Test output windows


The Users Guide
Although this example was rather simple, it is always necessary to include a brief users
guide with your code. A computer program, no matter how elegantly written, is useless
if no one knows how to use it. You should describe the user interface (will the user be
prompted to type some input? what is the output?). Assume that users have no clue of
what you are doing, they will simply follow your instructions.
The guide for our example would read something like this:

To execute the program, compile and run the file named: distance.c
The user will not be prompted to enter the 2 points coordinates; rather, these
values are hard-coded in the program.
The output displayed on the screen is the distance between the two points.
To modify the coordinates of the two points, change the values of the variables x1
and y1 (for point #1), and x2 and y2 (for point #2), which are found below the
comment line Declare and Initialize the variables in the program source.

GNG1101

Navigation in the Faculty of Engineering PC Lab


Laboratory facilities.
The computer laboratories will be held weekly in room CBY B02 where we have
available many IBM compatible personal computers running the Windows XP operating
system. The faculty computer laboratory is located in rooms CBY-B102, B105, B109,
and B111, where an additional number of computers are located. The operating system
used on these machines may be Windows XP. These facilities are for general use and a
computer is accessed on a first-come first-served basis. Our C compiler should be
available on all of these machines so you may use them to complete your assignments,
should you need them.
Activating your computer account.
You must activate your computer account before you can log onto the network and
access a personal computer. You must go to the faculty computing centre, room CBYB109 to activate your account. You will need your student number and your University
of Ottawa PIN number. You will find near room CBY-B109D, the necessary computer
running a Web-based activation form. Make sure that you do this as soon as possible and
at least 3 days before your first scheduled activity in the laboratory to ensure that your
account will be activated in time. Verify that your account has been activated before
your first lab by trying to log on to a PC in the faculty computer laboratory. To log on to
a computer you will need your userID (University of Ottawa e-mail user ID) and
password. You will obtain this information when you set-up your computer account in
CBY-B109. You will find your disk space on drive F:
Logging on to a Computer.
The following procedure is to be used to log on to one of the machines running Windows
XP.

Wiggle the mouse to remove the screen saver if it is on and to bring up the login
dialog box.
If the login dialog box is not displayed on the screen, then press the three keys: Ctrl
Alt Del simultaneously. All these keys are on the bottom line of keys on the
keyboard: Ctrl (Control) is on the extreme left, Alt (Alternate) is near to the right and
Del (Delete) is the second key form the right.
Once the dialog box is displayed, you can type your userID, in the top box, and your
password in the second box (your password appears as **** to prevent others from
reading it over your shoulder). You can select the box to accept keyboard input by
moving the cursor with the mouse and when the cursor is in the box, clicking on the
left button.

GNG1101

If this is the first time that you use your account, the computer will ask you to change
your password. You will have to enter the same information twice. This is to check that
the new password is correct, because all you see as you type is **** so nobody can
read over your shoulder.
When Windows stops loading, the hourglass to tell you to wait disappears and you can
start the Dev-C++ environment.
The Desktop.
Windows is a complex computer operating system. It allows for many programs to be
operating at the same time. The one you are looking at can be brought to the top of the
desktop. The screen is called the desktop as it simulates a desk surface with several
pieces of paper on it. The papers all lie on top of each other and it is the top one that you
can see completely. The same is possible on the computer. If you click the left mouse
button in any window that is covered by others, this window will be pulled to the top,
you can see it completely and it is now active.
Dev-C++ v4.01
The environment we have chosen for you to learn C is called Dev-C++. The reason for
choosing this environment is related to its excellent quality, and its price: FREE!. What
this means for you is that you can download the environment directly onto your home PC
and work quietly on your assignments and labs, with the same environment as the one
you will find on the engineering PC's or during the lectures. We hope this will help you
in your learning experience. You can download the whole package at the URL:
http://www.bloodshed.net/dev/devcpp.html
We recommend you to download version 4.0 along with the 4.01 update, since version
5.0 is still beta at the time this document was completed.
Starting the C Programming Environment: Dev-C++ v4.01
Move the cursor to the Start button on the bottom left of the screen. Click the left mouse
button. A pop-up menu appears with several items on it. Move the cursor to Programs. A
second popup menu will appear to the right. Move the cursor into the new menu, be
careful to move the cursor horizontally. If you move up or down you may activate a
different pop-up menu. Once in the new menu you can move up or down select
Programming. Again move into this menu and select Dev-C++. Finally in this last menu
select Dev-C++. This last item can be selected by clicking on the left mouse button. The
programming environment Dev-C++ will be started. Wait for the start-up of the program
to be complete by watching for the hourglass to disappear.
Using the Dev-C++ Environment.
Dev-C++ allows you to write your programs using a text editor and then to compile, link
and run them. You can for example code our hello world program, compile and run it
just to get familiar with the programming environment.

GNG1101

10

Creating aFile
To begin writing a program in the environment, you must first define a new file:
Move your cursor to the "File" item on the menu bar at the top of the environment
and click with the left mouse button. A pull-down menu will appear from which
you select "New Source file".
A new file window will appear with a name starting with Untitled as below:

Figure 1.5, the New Source file window

GNG1101

11

Writing a Program in the Environment.


The window of Fig 1.5 contains the bare minimum of a C program. You can start with
this skeleton to write your program.
You can edit (modify) a file by simply clicking anywhere in it and directly inserting text,
or erasing it with the backspace or delete keys. Use the keyboard to modify our original
file such that you get the following result:
/********************************************/
/* My Name, My Student Number
*/
/* Sept 1, 2003.
*/
/* Filename: hello.c
*/
/*
*/
/* This program prints out the message:
*/
/* Hello World! on the screen.
*/
/********************************************/
#include <stdio.h>
int main()
{
printf("Hello World!\n");
system("PAUSE");
return 0;
}

Here the lines:


#include <iostream.h>
#include <stdlib.h>

have been removed as well as the other lines having been added.
Take care in not forgetting the semicolons ; at the end of many lines. For now, this
might not make much sense to you, but soon you will be able to understand it. We can
tell you already that the top part (all lines enclosed between /* and */ are comments
that help whoever is reading your program (a friend, or yourself in few months) to better
understand its content. You can put anything there, and you can add as many comment
lines as you want, as long as you enclose them with the pair /* and */.
Saving Your Program.
When you have typed in your program you should save it in order to keep your work for
the next session. You have two disks available to you, the 3.5" floppy you have brought
with you as disk A: and space on the system disk called F: the choice is yours here. Lets
first save to F: To save to F: you can:
click on File on the top menu bar and then click on "Save unit".
Note that in order to save the program, the text editor window must be active; to activate
this window you simply click your mouse in it. As this is the first time you have saved
your file (it still has a name starting with Untitled), DevC++ will ask you for the name

GNG1101

12

of the file. Lets save it to hello.c. DevC++ will offer you the extension cpp for C++.
You should force the name to hello.c by typing all of the name.
Let's save to a floppy now, which corresponds to the unit A. Select File on the menu
bar. Select "Save unit as..." and in the file name dialog box type A:\hello.c then click
on Save. If you get an error that your disk is not ready check that you have properly put
in a formatted disk.
Each modification you make on a file is NOT automatically saved in your file. SO
DO NOT FORGET TO SAVE YOUR FINAL WORKING TEXT FILE AT THE
END OF A SESSION. SAVE OFTEN AS COMPUTER SYSTEMS ARE
VULNERABLE TO FAILURES.
Compiling, Linking and Running the Program.
Now that you have saved your text file, you can run it. Press on the Execute menu item
and choose "Compile and Run Project". Dialog boxes will appear to tell you what is
happening during compilation and linking. If all goes well, the program will run. See
below for correcting simple syntax errors.
Console Window.
When your program runs, a DOS (black) window will appear to printout the output.
Also, any input you offer will be seen in this window. In the case of our program,
Hello World! should appear at the top left corner of the window When your
program completes, you will also see Press ENTER to continue.... This was
also part of our program, and was put there to allow you to visualize the output. Indeed,
without the line:
system ("Pause");

The window would have closed immediately, without leaving you the time to look at it.
You can try to comment out this line (by putting /* at the beginning and */ at the end)
and see what happens. In fact, we recommend you to always put this line at the end of all
your programs, in the main module, just before the return 0;.
Once you are done with looking at the result, press any key and the window will close
automatically. To go back to Dev-C++, press the corresponding button in the bottom
taskbar of Windows. A small window named "Compilation completed" will be still
there. Just press "Continue" to make it disappear.

GNG1101

13

Icons.
To help you run your programs faster, most of the menu items are available as icons
small graphics images that react to a mouse click. There are two icon sets (found under
the menu item Options). Here are the most common icons to use:

Fig 1.6 The two icon sets (default top and Gnome bottom)
showing the location of major icons.
Errors.
When your program runs, a DOS (black) window will appear to show the output. If
Dev-C++ finds an error in your program while compiling it, you won't see the DOS
window appear. Instead, the small window identified as "Compilation completed" will
remain. In this window, you will see "Total errors", and then a number next to it. This is
the number of errors Dev-C++ has found in your program. You can press "Continue"
and this window will disappear. Each detected error will remain in a list at the bottom of
the screen. If you double-click on an error, the corresponding line will be highlighted in
your file. Beware though that the compiler does not always find the right position for
your error, and it might be on another line. So for now, just verify with the text given in
this document to find any typo you might have introduced. Again, check for any missing
semicolon. Other common errors are: missing opening and closing brackets.
If your program has run perfectly the first time, congratulations! You might want to
introduce yourself an error to visualize what happens. Remove one semicolon for
example and see what happens.

GNG1101

14

Further Help.
See under Help, Help on DevC++, or the Tutorial (very simple), Contents, Index and the
appropriate subject. The online help is very succinct, but helpful. You can also find
more help at:
http://www.bloodshed.net/dev/doc/index.html
Most of the documents available there treat with general C/C++ issues, and not
necessarily with Dev-C++. But do not worry, as the amount of information you will need
to use Dev-C++ in our course is quite simple.
Simple Word Processing: Wordpad.
The same word processor can be used to show a listing of your program, its output and
for writing your software report. The simple word processor WordPad is available on
Windows. To run WordPad, click on: Start, Programs, Accessories and select WordPad.
After opening WordPad, you may copy your program from the Dev-C++ text editor to
WordPad by performing the following:
Bring Dev-C++ to the top of the desktop by clicking somewhere in the Dev-C++
window or clicking on the Dev-C++ icon on the Windows Taskbar (the area
along the bottom of the screen).
Click in the text editor window to select it.
On the menu bar, click on Edit, Select all, Edit and copy.
Bring WordPad to the top of the desktop.
Click to place the cursor where you want the program to appear.
On the menu bar in WordPad, click Edit and Paste.
Once your program is pasted into your document, you should highlight the text and select
courier as the font for displaying the program listing as it will appear more clearly in your
report.
To get a copy of the console window into WordPad you should perform the following:
Run your program and when done ensure that the console window is selected by
clicking in the window.
The next step is to copy the window to a holding area called the Clipboard by
pressing the Alt PrintScrn keys at the same time (PrintScrn - Print Screen is on
the top row on the keyboard, next to F12).
Now enter WordPad and paste your output from the Clipboard at the cursor
position using Edit and Paste.
The following is the output window of the Dev-C++ environment as it would appear in
your report:

Fig 1.7 The output screen of the Hello World example program

GNG1101

15

You may save the contents of WordPad by using File and Save as and giving an
appropriate filename on disk A: or F: WordPad can be used to save your programs and
outputs and to write your report. Soft copies of your work will save you time and money
as you will not need to do so many paper prints.
Wordperfect.
The WordPerfect word processor is also available on some of the computers if you prefer
something a little more sophisticated. Follow the instructions as for WordPad, except
click on Start and Corel WordPerfect.
Logging Off.
You should close all your programs using File and Exit. Then logoff using the Logoff
icon on the desktop. DON'T FORGET TO SAVE ALL IMPORTANT FILES TO YOUR
DISKS BEFORE YOU CLOSE DOWN PROGRAMS.
Printing Hard Copies of your Programs.
If desired, you may print hard copies (printouts) of your programs and reports at the
University; however, you must pay for every page that is printed. The campus-wide
printing system, which is used by the computer lab network, is called RELMON.
RELMON printing stations are located at various places throughout the University of
Ottawa campus, but the closest one is right outside the computer labs main doors near
CBY B109 (the next closest station is in the basement of Marion Hall find it before you
urgently need it!). A list of the other printing stations locations should be posted beside
the RELMON station outside the lab. To print hard copies, you must have a copy card
(the same card that is used by the photocopiers throughout the campus). You may obtain
a copy card and put credit on it at any copy card machine. One such machine is located
in the basement lobby of Colonel By Hall (next to the photocopiers) and another is
located at the Morisset Library.
When you print from one of the PCs in the lab, the file is placed on the RELMON queue.
To print the actual hard copy, you must insert your copy card in the RELMON card
reader and follow the directions given at the printing station. You may delete your file
from the queue without inserting your copy card.
Note: Once your file is on the queue, you may print it from any one of the RELMON
stations throughout the campus.
Additional information can be found in the RELMON guide published by the Computing
and Communications Services of the University of Ottawa. Additional information can
also be found in course WEB site in Links as:
Guide to the Relmon Self-Service Printers
or

http://www.uottawa.ca/services/ccs/docs/cyberleap/relmon/relmone.html

GNG1101

16

Handing in Your Laboratory Report.


Your laboratory report is to be handed-in electronically via the GNG1101 website. Send
your file to your TA using the course websites "Dropbox". Laboratory reports will be
accepted as Wordpad readable documents only. If you use another wordprocessor, please
save the file in a Wordpad readable format before submission. Your lab report must be
prepared according to the format described in the previous section and thus will contain
the program listing as well as the output windows that prove that your program is
working. Only one file per lab is thus to be sent in.
Sending in Your Report Using the Course Websites "Dropbox"
1. From the GNG 1101 home page click on the Dropbox icon or the Lab submission
item in the left hand frame.
2. Click on Laboratory 1 for the first lab, use the appropriate link for the other labs.
3. Click on Student files.
4. Click on Upload.
5. Use the Browse button to locate your report file.
6. Click on Upload.
7. Check that the screen shows that the correct file has been uploaded and then click on
Laboratory 1 near the top of the page (or whatever is the appropriate lab).
8. Click Submit.
9. Provide an e-mail address if you want an acknowledgement of the receipt of your lab
(recommended - keep the reply safely in case your lab gets lost).
10. Check that the file listed for submission is correct - you only get one opportunity to
submit each lab.
11. Click Submit assignment.
You are responsible for ensuring that your lab report is sent correctly. To be sure that
you understand the above procedure, prepare a document for the following tutorial and
submit it to Tutorial 1, your submission will be acknowledged so you know that it
workded.
Getting Feedback on Your Laboratory Reports
After your laboratory submission has been marked, the marks will appear in your grade
record found by clicking on the My grades icon. Also, if you return to the Lab
submission page and your report has been graded, the status will say "Graded",
pressing on this word will show you what you submitted, your marks and any comments
that have been provided by the TA.

GNG1101

17

2. Tutorial 1.
Since this is your first lab session, spend some time investigating the operating system
(OS) and the C compiler. Once you are familiar with the environment, begin working on
the computing assignment. This weeks assignment is described below. This is a tutorial
assignment and is not to be handed in to your TA.
Programming aspects to get familiarized with:
- how to use the editor/compiler and to perform simple keyboard/screen input/output
- perform simple arithmetic calculations
Temperature Conversion
-

BACKGROUND

In 1708, (Gabriel) Daniel Fahrenheit (Germany: 1686-1736) adopted a fixed point scale
of temperature. The Fahrenheit scale sets the zero at the freezing point of a salt-water
mixture and 100 at approximately body temperature.
In 1742, Anders Celsius (Sweden: 1701-1744) described a mercury thermometer that had
the zero of the scale set at the freezing point of pure water and 100 degrees set at the
boiling point of pure water. The Celsius system is sometimes referred to as the
centigrade system.
The Kelvin scale, named after Lord Kelvin (William Thomson) (Scotland: 1824-1907),
sets zero at the absolute zero of temperature (at which the motions of atoms and
molecules practically stops) and uses degrees that are the same size as the Celsius
system.
The Kelvin scale is related to the Celsius scale by the following relation:
TK = TC + 273.2
where TK is the temperature in Kelvin and TC is the temperature in C.
The Celsius scale is related to the Fahrenheit scale by:
TF = ( TC * 9/5 ) + 32
where TF is in F.

GNG1101

18

ASSIGNMENT

Write a program that can convert a temperature in degrees Celsius to degrees Fahrenheit
and Kelvin. The user should be prompted to enter the temperature in degrees Celsius and
the program should print on the screen the temperature in degrees Fahrenheit and Kelvin.
Write a second program, but this time ask the user the temperature in Fahrenheit and
convert it to Celsius and Kelvin. Use your first program as a template. Using the editing
tools (copy and paste), copy some lines from program1 to program 2.
Prepare a short laboratory report just to make sure that you know how to incorporate all
of the required elements into your document (diagrams, program listing and output
windows). Send the report to yourself as an attachment (see Chapter 1 of this lab manual)
using the course website and read your mail with the attachment to make sure that you
have sent in your document correctly.

GNG1101

19

3. Computer Laboratory 1: Computing Course Grades


-

BACKGROUND

From the course outline, the final mark for the course GNG1101 is computed using the
following algorithm:
M x = 0.2 Midterm exam + 0.8 Final exam
if M x 50, Final mark = M x
M 2x + 350 M + 7 Labs M x 350 Labs
x
if 50 < M x < 70, Final mark = 0.125

Mx

if M x 70, Final mark = 0.75 M x + 0.25 Labs

ASSIGNMENT

A program is needed to compute the course marks of all the students in a lab section of
GNG1101.
Within a loop, the user should be prompted to enter the midterm mark, the final
examination mark and 5 lab marks (all marks entered are on 100); your program should
then respond by printing to the screen the final mark for the course on 100, computed
using the marking scheme described above. Looping must end and your program should
terminate when the user enters a negative value for the midterm mark.

GNG1101

20

4. Computer Laboratory 2: Vector Mechanics


-

BACKGROUND

Problem solving and the computer are tools to be used throughout your program of
studies and your career. Although you will be exposed to different ideas in different
courses, you must integrate these into a whole so that you can be a successful engineer.
In an attempt to show the usefulness of the ideas of GNG1101 to other courses and to
start you thinking about integration, Laboratory 2 has been taken from the course
GNG1100 Engineering Mechanics.
-

ASSIGNMENT

The piston and its connecting rods shown in figure P3.8 are taken from Question 3.8 of
the book Vector Mechanics for Engineers by Beer and Johnston. The question states
It is known that the connecting rod AB exerts on the crank BC a 2.5kN force directed
down and to the left along the centerline of AB. Determine the moment of the force
about C.

GNG1101

21

This question considers the piston at one instant in time. With the computer we can
determine the moment at many positions. This laboratory exercise will do just this by
presenting a table of the moments for a set of positions of the piston. The range of
positions to be used is from a starting position close to that shown in Fig. P3.8 to the final
position shown in Fig. 4.2 where the crank BC has become horizontal. The crank moves
from the start to the final positions by B rotating about C in a counterclockwise direction.
To aid in the trigonometry of the system, two extra points have been marked as X and Y.
If we are to produce a table, we will want to use a looping structure and allow some
feature of the piston system to be changed with the calculations for moment being carried
out for each value of this changing feature. A useful feature, and the one to be used in
this laboratory, is the angle BCY. This is the angle of the crank with respect to the
horizontal. For this laboratory, we shall start with an angle of 50, which is close to the
position shown in Fig P3.8, and end at the value 0 as in Fig. 4.2.
-

PROCEEDURE
1. Write a looping structure that runs from the starting angle to the end angle in
steps of 2.5 degrees, keep your angles in degrees but remember that the math
libraries use radians for all calculations with angles.
2. Calculate and print a table that lists the angle BCY and the corresponding
moment about C. Take care with units. Assume the 2.5kN force is constant in
magnitude and always acts along AB.

- QUESTIONS
1.
Where is the maximum moment?
2.
What special feature does the position of the system possess when this maximum
occurs?
3.
What direction are the moments within your table?
4.
What solutions are put in place in a real engine to smooth out the variations of
moment acting on the crank?

GNG1101

22

5. Computer Laboratory 3: Product Reliability


-

BACKGROUND

An analysis of the reliability of a piece of equipment is especially important if the part is


going to be used in situations that would be dangerous if it should fail (e.g. industrial
plants, devices used by the general public, etc.), or in environments that are not easily
accessible (e.g. remote locations, underwater, space, etc.).
Equations for analyzing the reliability of instrumentation can be developed from the
study of statistics and probability. Reliability is defined as the proportion of time that the
component works properly. Thus, if a component has a reliability of 0.8, then it should
work properly 80% of the time. The reliability of combinations of components can also
be determined if the individual component reliabilities are known. Consider the
diagrams shown in Figure 5.1 below. For successful operation, all three components
between terminals IN and OUT must work properly in the series design. In the parallel
design, only one of the three components must work in order to have successful
operation. If we know the reliability of an individual component, then the reliability of a
specific combination of components can be determined in two ways: an analytic
reliability can be computed using theorems and results from probability and statistics, or
a computer simulation can be developed to give an estimate of the reliability.

Figure 5.1 Configurations: Series (top) and Parallel (bottom)


Let r denote the reliability of one of the components, and let all of the components have
the same reliability when taken separately. It can be shown that a three-component series
combination (as illustrated in Figure 5.1) will have a reliability of r3. Thus, if the
reliability of each separate component is 0.8, then the system reliability in the series
combination is 0.83=0.512. Thus, the series configuration should work properly 51.2%
of the time.

GNG1101

23

If these same components are arranged in the parallel configuration, then it can be shown
that the reliability of the three-component system is r3 - 3r2 +3r. Thus, if the reliability
of each separate component is 0.8, then the analytical reliability of the parallel connected
system is 0.992. The parallel configuration should work 99.2% of the time.
We can also estimate the reliability of these two designs using random numbers from a
computer simulation. First, we need to simulate the performance of a single component.
To simulate the performance of a component that has a reliability of 0.8, we could
generate a random floating-point number between 0 and 1. If the value is between 0 and
0.8, we can assume that the component worked properly; otherwise, it failed. (We could
also have used the 0 to 0.2 interval for a failure, and 0.2 to 1.0 for a component that
worked properly.)
To simulate the series design with three components, we would generate three of these
random numbers. If all three numbers are less than or equal to 0.8, then the design works
for this one trial; if any one of the numbers is greater than 0.8, then the system does not
work (fails) for this one trial. If we run hundreds or thousands (or millions.) of trials, we
can compute the proportion of the time that the overall design works. Remember that
this simulation estimate is only an approximation of the analytically computed reliability.
To estimate the reliability of the parallel design with a component reliability of 0.8, we
again generate three random floating-point numbers between 0 and 1. If any one of the
three numbers is less than or equal to 0.8, then the design works for this one trial if all of
the numbers are greater than 0.8, then the design does not work for this one trial. To
estimate the reliability determined by the simulation, we divide the number of trials for
which the design works by the total number of trials performed.
As the number of trials computed increases, the simulated reliability should approach the
analytical value. Note that there are cases in which it is very difficult to compute
analytically the reliability of a system. In these cases, a computer simulation similar to
the one you are about to write can be used to provide a good estimate of the reliability.

GNG1101

24

ASSIGNMENT

1. Develop a program to compare the analytical reliabilities of the series and parallel
system configurations in Figure 5.1 with simulation results. Allow the user to enter
the individual component reliability and the number of trials to use in the simulations.
Assume that there are exactly three (3) components in the system and that they all
share the same reliability as specified by the user. Perform testing to determine the
best parameters (number of trials, random seed) to provide estimates comparable with
the theoretical values.
2. Program the following compound system and estimate its reliability

Figure 5.2 Compound system

GNG1101

25

6. Computer Laboratory 4: Mechanical Engineering Case Study


The implementation of a case study from Mechanical Engineering. The objective is to
calculate the fuel necessary to send a 50 kg payload to Mars.
- BACKGROUND Consider the rocket at two times:

At time = t:
At time = t+t:

mass = M
and velocity = v
mass = M-M and velocity = v+v

Observer

Fig 6.1 Diagram showing the rocket at two successive times


The velocity of the rocket increases as the engine expels gases into space. The mass of
exhaust gas expelled in the time t is M. The exhaust has a velocity of u away from the
rocket when measured from the rocket. To the observer who sees the rocket velocity as
v, the exhaust has a velocity of v-u.
By conservation of momentum, the momentum at time t and t+t must be the same:
Mv = (M M )(v + v ) + (M )(v + v u )
Mv = Mv + Mv uM
Mv = uM
v
M
M
=u
t
t

(Note: at the moment of release of the exhaust mass M; the rocket and the unburnt fuel
are travelling at v+v, while the exhaust is travelling at v+v-u.).

GNG1101

26

If we now include external forces, we can write:


M

v
M
=u
Mg
t
t

where the only external force we have considered is that of gravity, Mg, working
against the upward movement of the rocket.
If we now perform a piecewise approximation in intervals t, we obtain the equation for
the change in velocity v:
u M
t gt
M t
u
v =
Rt gt
M

v =

Note that we have maintained

M
t

as a term, this represents the burn-rate of the fuel, R.

We are now in a position to make some calculations concerning the rocket.


We know:
1. the payload Mp = 50 kg;
2. the final velocity of this payload must be at least the escape velocity
(40000km/h);
3. the initial velocity of the whole rocket, payload and fuel (Mp+Mf), before engine
burn: = 0m/s
4. the velocity of the exhaust gases relative to the rocket: u = 4000 m/s;
5. the gravitational constant g = 9.81 N/kg.

We do not know the mass of fuel Mf.

We can use the computer to iterate1 the above equation to calculate the mass of fuel
needed to free the payload from the Earth.

Iterate: to repeat. Used in computing to mean: carry out repeated calculations with one of the parameters
(in our case time) made smaller in each calculation until the difference between successive answers is
below some defined small quantity.

GNG1101

27

- ASSIGNMENT Proceed as follows:


1.
Start at the end! We know the final mass (Mp) and velocity (40000 km/h);
2.
Choose a burn-rate (R) and time interval (t), calculate the change in velocity
over the last interval (v), and update (backwards) to calculate the total mass and
velocity before that fuel was burned.
3.
Repeat step 2 until the velocity has reached the initial velocity of 0 m/s.
4.
Verify your estimate by reducing the step size (t) by dividing it by 2 and
recalculating.
5.
Stop when the estimate varies by only 1 kg.

Ensure that the units are consistent.


Ensure that your answers are sensible.
What happens if the burn-rate is too low to overcome gravity? How will your
program indicate this?
Try different burn-rates.
Which burn-rate do you find best?
Build in a margin of error on your "best" burn-rate so that a real rocket based on your
design will attain at least escape velocity.
How long does the engine run?
What is the maximum acceleration?

GNG1101

28

7. Computer Laboratory 5: Civil Engineering Case Study.


The lab is the implementation of a case study in Civil engineering, which deals with
dynamic structures under earthquake excitation.
- BACKGROUND An idealized floor of lumped mass (m) is supported by a massless structure as shown in
cross sectional view of Fig 7.1.

Fig 7.1 Ideal building structure


The supporting structure provides the vertical force necessary to support the floor and
some lateral stiffness k. The imaginary dashpot models the damping (c) in the structure.
We assume that the floor is made out of concrete and the supporting structure consists of
light steel pipe; thus any motion in the lateral direction is due to the flexibility of the
pipes. Suppose now that our structure is subjected to an earthquake which causes a
lateral motion only in the ground supporting the structure. The lateral motion in the
ground will cause a lateral motion in the floor which is modeled as shown in Fig 7.2.

Fig 7.2 The ideal structure under deformation


The total lateral displacement of the floor relative to its rest position is given at each
instant of time t as ut(t). The displacement of the floor relative to the loss of its
supporting structure is given as u(t) and the displacement of the ground relative to the
rest position of the structure is given by ug(t). What is interesting from the structural
GNG1101

29

dynamics point of view is the motion of the floor relative to the base of its supporting
structure owing to the earthquake. The equation of motion governing the relative
displacement of the floor u(t) subjected to the ground acceleration g(t) is given by:

mu&&(t ) + cu& (t ) + ku (t ) = mu&&g (t ) = P


where m is the mass of the floor, c is the damping in the structure and k is the lateral
stiffness.
The equation of motion is a linear second order ordinary differential equation in u(t)
which has an analytical solution if g(t) is known analytically. The trouble with
earthquakes is that they generate ground accelerations which are some what random in
nature, thus g(t) is not known analytically but rather as a sequence of data points at
regularly spaced times ti g,i(ti). Thus, the equation of motion subjected to an earthquake
must be solved numerically using so called time stepping methods. One such method is
Newmarks method for which the algorithm is given below.
Two cases for the method exist as shown; an average acceleration case (=1/2, =1/4)
and the linear acceleration case (=1/2, =1/6).
The initial calculations (1.0) in the method are based on the initial conditions for a floor
which prevail at the time to, just before the occurrence of the earthquake. Clearly, at the
time t0=0 sec the floor is at its rest position and has no initial velocity: u 0 = 0, u& 0 = 0 .
The time interval t is the interval for which we have ground acceleration data.

GNG1101

30

NEWMARK'S METHOD: LINEAR SYSTEMS


Special cases
(1) Average acceleration case (= 1/2, = 1/4)
(2) Linear acceleration case ( = 1/2, = 1/6)
1.0 Initial calculations
p0 c u& 0 k u 0
1.1
u&&0 =
m
1.2
Select t
1

1.3
k = k +
c+
m
t
(t )2
1.4

a=

1
1

1c
m + c; and b =
m + t
2
t

2.0 Calculations for each time step, i


Pi = Pi +1 Pi
p i = pi + a u&i + b u&&i
2.1
p i
ui =
2.2
k

2.3
2.4
2.5

u&i =


u&&i
ui u&i + t 1
t

1
1
1
ui
u&i
u&&i
2
t
2
(t )
ui +1 = ui + ui , u&i +1 = u&i + u&i , u&&i +1 = u&&i + u&&i
u&&i =

3.0 Repetition for the next time step. Replace i by i+1 and implement steps 2.1 to 2.5 for
the next time step.

GNG1101

31

- EXAMPLE Suppose that our floor has a mass of m=0.2523 kg that lateral stiffness of the structure
k=10 kg/s2 and the damping c=0.1592 kg/s. Our floor is subjected to a hypothetical
earthquake producing the ground force shown below:
12

10

10

8.66

P(t), N

8.66

4
2

0
0

0
0.1

0.2

0.3

0.4

0.5

0.6

0.7

time (t), sec

Apply by hand Newmarks method in the times ti, 0 i 10 using the average
acceleration case and fill in the following table for our hypothetical earthquake. Check
your answers.
Average acceleration case (= 1/2, = 1/4)
1.0 Initial calculations
u 0 = 0, u& 0 = 0, P0 = 0
p0 c u& 0 k u 0
=0
1.1
u&&0 =
m
t = 0.1sec
1.2
1

k = k +
c+
m = 114.5
1.3
t
(t )2

1.4

a=

GNG1101

1
1c = 0.5066
m + c = 10.45; and b =
m + t
t

2
2

32

2.0 Calculations for each time step, I


i
0
1
2
3
4
5
6
7
8
9
10

ti
Pi Pi
ui
i
i
Theoretic
ui
i
i
2
2
(s) (N) (N)
ui (m)
(m)
(m/s) (m/s ) (m) (m/s) (m/s )
0
0
5 0.0437 0.873 17.467
0
0
0
0
0.1
5
0.0328
0.2 8.66
0.2332
0.3
10
0.6487
0.4 8.66
1.1605
0.5
5
1.5241
0.6
0
1.4814
0.7
0
0.9245
0.8
0
0.0593
0.9
0
-0.7751
1
0
-1.2781

GNG1101

33

- ASSIGNMENT Write a program to implement Newmarks method. Your program must prompt the user
for the mass m in kg, the damping factor c (in kg/s) and stiffness factor k (in kg/s2). It
must also prompt the user for the case of Newmarks method to be executed: 1- for the
average acceleration case or 2- for the linear acceleration case. Your program must read
sequentially ground acceleration data (in m/s2) from a file as Newmarks method
progresses, until the end of file is reached. Do not read the entire file in memory. Your
program must output to the screen the value of the maximum lateral force in the
supporting structure encountered during the earthquake. This force is given simply by
k.u(max) where u(max) is the maximum relative displacement that occurred during the
earthquake. The first line of the file is a comment line which must be skipped, the second
line of the file is the time t and the remaining lines contain the ground acceleration at
sequential.
- TESTING Create an input test file that contains the ground acceleration values for our hypothetical
earthquake. Your file should look like:
Ground acceleration data hypothetical earthquake
.1000
-19.7394
-34.1887
.
.
.
0.0000
(eof)

Remember: P = mu&&g (t ) for P1=5N, with m=0.2533Kg, g(t)=-19.7394 m/s2


Run your program for this test file and compare your data at each iteration with your
theoretical computations. The maximum lateral force in the supporting structure should
be seen (10)(1.5241) = 15.241 N.
Run your program for the files cal.dat and mex.dat which contain ground acceleration
data for the 1994 California earthquake and 1995 Mexico earthquake respectively. You
must include in your report the maximum lateral force to which the supporting members
of our floor would have been subjected.

GNG1101

34

Vous aimerez peut-être aussi