Você está na página 1de 16

Computer Science Class

Master SMA/STEU/GC/AMASONE

Lab and Homework 1

2015

General instruction for all lab


See resource Assignment in https://hippocampus.ec-nantes.fr Labs section of M SMA PROLA
course for due date and delivery.
Your work is sources answering to exercises given below. They must be provided as individual
text files following naming convention of your subject. For each exercise a table, called requested
information table hereafter, sets precisely what is expected in terms of naming convention, precises
order of input data for the programs you create and output format of these programs results (see
chapter 8.4 for complete explanations). You are expected to upload an archive containing all your
work in resource Assignments of course Labs section of Pedagogic server (no individual file will
be allowed)
An auto evaluation tool called auto eval.bash (see chapter 8.1, 8.2, and 8.3 for details) given
with this document, has to be used to generate this archive. It can also be used to auto evaluate
your archive before submission and check partially correctness of your work.
The same auto evaluation tool will be used by the teachers to evaluate your work.

Failure to return the sources archive on time on the server will result in a grade
of zero for this homework.
Uploading an archive with a wrong structure or name (i.e. archive not readable
or not named correctly) will result in a grade of zero for this homework.
Note : Some useful tricks are given in chapter 8.5.

Specific instruction for this lab


The two unnumbered following chapters are not graded. They are just training exercises to start
practice.

Training - Getting familiar with the console and linux.


Below are some training exercises. Dont spend too much time on those little training
exercises. The purpose of these is that you can start.
Do the following :
Open a terminal (browse menu to find this program). Then click inside this window. Thats
it you are now interacting with Linux command interpreter !
In your home directory (where you arrive if you just type cd ) type :
> mkdir -p ComputerLab/lab1
then get into this new folder :
> cd ComputerLab/lab1
then type :
> gedit hello.cc

(or any other editor than gedit that you want)

and pass to next training

You can come back to the following later on :


Using the console create a directory named ComputerLab in your home directory. Inside this
directory create a directory named lab1. Edit a file (use for instance gedit) named test1.txt, put
whatever you want inside it. Using the console, try to change its name. Try to copy it in your
home directory. Modify this file on the home directory, copy it with the name test2.txt in the
ComputerLab/lab1.
Look at the rights you have on the file. Change your rights on the file to read only, try to
modify the file using an editor. You can use your one-sheet linux survival guide to help you do
that. Remember that you can get a complete description of each command using the command
man, or a short help by adding - - help or -h at the end of the command.
There is much more that can be done within the command line. Even complicated scripts can
be written to help you do repetitive tasks. The command language usually used on Linux is the
bash (born again shell).
When you have time, you can learn more tricks with the console. For example, for shell script,
you can have a look here.

Training - First program.


Write a hello word program (a program that print hello world on the screen), something similar
to the first c++ program that we have seen in class. Make sure you understand all the commands.
Compile it, correct it if it needs to be. Execute it. Try to add errors in the program. Compile
it. Try to understand the error messages.
As it is just training no source are requested for evaluation.

1
1.1

A simple program.
First basic Input/Output

Write a program basic io that ask for your year of birth and then print it on the screen. You'll
need to look at course C2 for basic i/o and eventually take a look on the net to complete. Modify
your code so that it also asks for your weight in kilograms, and then print it out.

1.2

Input/Output string

Modify your program so that it also asks for your name and then displays all those three informations following requirements below. Force you to have a program which first ask 3 questions then
print 3 outputs.
You'll need to store your name in a variable which is an array of char. Declare for that
char myname[10]; in your code. Which means that myname is an array of 10 characters.
See what happens if you reply something much longer than 10 characters. Try 11, 15 then a
very long sequence of characters.
Requested information
Files
Input
Output

basic io.cc
year of birth, weight then your name
NAME(name) YEAR(year of birth) and WEIGHT(weight)

Scaling : 1/16

Coordinates of a point in a given cylindrical coordinate


system

A cylindrical coordinate system is a three-dimensional coordinates system corresponding to the


extension of the two-dimensional polar-coordinates by a height axis. We will use (, , h) as point
position in this system. More precisely we will look at , the distance from the system reference
axis, and h the distance from the system reference plane perpendicular to this axis. We will not
compute .
Write a point coord program (stored in point coord.cc) to compute the coordinates and h
in a given cylindrical coordinates system C for any point P of space, both chosen by the user.
All information asked by point coord to the user will be using coordinates (x,y,z) of an arbitrary
point P in a global Cartesian coordinate system R. point coord will use a partial definition of C
as is not computed. Only the C height axis direction and the origin point O will be given.
Requested program input/output
Input
A point O, the origin of C . It corresponds to three real numbers
xO , yO and zO .

A point D such that OD describes C height axis direction. It


corresponds to three real numbers xD , yD and zD .
The testing node P . It corresponds to three real numbers xP , yP
and zP .
Output
Point P coordinates p and hp in C system.

Depending on the user entries, C may be completely indefinite and computation impossible

if kODk is null. In this case the calculations resumes to set p and hp to zero. Having input
information the program must check this aspect first and give a message M according to the
situation:
HEIGHTAXIS : null

if kODk < 1.e10


3

HEIGHTAXIS : notnull
otherwise. Then the program computes and outputs p and hp .
All the operations will be done using real double precision variable. Obviously you will need
to take the square root of a double at some point. Some basic mathematical functions are part of
the C++ norm and are declared by adding at the top of your source the line #include <cmath>.
You can use then ... sqrt(x) ... to compute the square root of a x variable. Many other
operations like trigonometric,logarithmic or power of real numbers are present in this header (see
http://www.cplusplus.com/reference/cmath).
Requested information
Files
Input
Output

point coord.cc
xO , yO , zO , xD , yD , zD , xP , yP then zP
RHO(P ), HEIGHT(hP ), HEIGHTAXIS(M)

Scaling : 3/16

Car price

Imagine a company that sells utilities of different brands and colors. This company wants a program
to help its sellers. It must give car prize (in euros) according to the table bellow by just asking the
brand and color.
Changfeng
Lada
Tata
Toyota

Black
9730
8780
10350
11350

Brown
9800
8600
10300
11650

Dark green
9990
8600
10400
11650

Write that car price program (stored in car price.cc) so that it asks for brand and color as
numbers according to their order in the table above. Says 1, 2 and 3 for black, brown and dark
green respectively. And 1,2,3 and 4 for Changfeng, Lada, Tata and Toyota respectively.
Here is an expected behavior example :
Enter brand (1 Changfeng, 2 Lada, 3 Tata, 4 Toyota ) :
4
Enter color (1 Black, 2 Brown, 3 Dark Green ) :
2
CARPRICE : 11650
If the user doesnt give correct numbers for brand and/or color the program must output WRONG
ENTRY instead of a price as it is illustrated below.
Enter brand (1 Changfeng, 2 Lada, 3 Tata, 4 Toyota ) :
9
Enter color (1 Black, 2 Brown, 3 Dark Green ) :
1
CARPRICE : WRONG ENTRY
The aim of this practical exercise is to make you use conditional structures in your program.
Note for those who want to simplify their solution, that the use of only one conditional structure
is possible to answer to this question.
4

Requested information
Files
Input
Output

car price.cc
brand then color
CARPRICE(price or WRONG ENTRY)

Scaling : 3/16

First functions implementation.

The purpose of this exercise is to get familiar with the way functions are declared and implemented
from a storage point of view (i.e. library concept, headers, implementation files . . . ). Its really
short. Dont search for algorithmic complication but be sure to correctly understand it because
library concept will be used in all the following labs.
Write two functions, named maximum and minimum. maximum must return the maximum of
the two double given as inputs of the function. minimum must return the minimum of the two
double given as inputs of the function.
The two functions must be declared in a header file named mathfunction.h and implemented
in a separate mathfunction.cc file.
The mathfunction.cc can be compiled using the following command :
> g++ -c mathfunction.cc
This will produce a mathfunction.o file. Note that this file is not an executable. It is called an
object file. mathfunction.o file corresponds to a kind of files used in library. A library groups .o
files to form an archive. The compiler may then use it at the linking stage to finalize compilation
of a program using some implemented functions present in that library. Here (and in the next
labs) we will just use the .o files without generating the archive but think of this(these) file(s) as
a library.
To test your maximum and minimum functions, you need to create a main program test mathfunction
that calls them with two double a and b asked to the user and outputs the result of their computation on the terminal (following requirements below). You will write it in a test mathfunction.cc
file. When it's done you can compile it :
> g++ -c test mathfunction.cc
This will produce the file test mathfunction.o.
You can now produce an executable by linking test mathfunction.o and mathfunction.o :
> g++ mathfunction.o test mathfunction.o -o test mathfunction.exe
Requested information
Files
Input
Output

mathfunction.h,mathfunction.cc,test mathfunction.cc
a then b
Maximum(max(a, b)) and Minimum(min(a, b))

Scaling : 1/16
Here test mathfunction.o may be of great interest only in large projects where you are compiling
not one, but hundred of programs, or if compilation of the main itself is very very long. Then you
are happy when you do a modification in a shared library not to compile again all the programs but
just link their associated .o files with the new library. This saves compilation time.

In our case we may shorten the compilation step by using the following commands as test mathfunction.cc
is obviously very quick to compile:
> g++ -c mathfunction.cc
> g++ mathfunction.o test mathfunction.cc -o test mathfunction.exe
And again as in this case mathfunction.cc is also obviously very quick to compile, we may even
be shorter :
> g++ mathfunction.cc test mathfunction.cc -o test mathfunction.exe
But this alleviates all the advantages of the library concept which is here among many things
to avoid as much as possible re compilation of unchanged sources. In the following labs you will
quickly adopt this concept to avoid losing time waiting compilation to finish.

Library concept

This exercise is somehow a continuation of exercise 4.


In this exercise, you must reuse the code that you have produced so far in exercise 4 and 2.
Starting from exercise 4 implementation you must generate mathlib.cc and mathlib.h containing
maximum and minimum functions.
Then you will add a function named pointcoord which does the same computations as asked in
2. Use only array type parameters to exchange information with this function as described below
:
Requested pointcoord function input/output
Input
1. An array AP of double containing P Cartesian coordinates in R
(modified on output). The storage order must be the following :
xP , yP then zP .
2. An array of double containing O Cartesian coordinates in R (unchanged on output). The storage order must be the following : xO ,
yO then zO .
3. An array of double containing D Cartesian coordinates in R (unchanged on output). The storage order must be the following : xD ,
yD then zD .
Output

The function must return an int :


1 computation was impossible because the given height axis
direction is null(in the sens of exercise 2). P and hP were set to
null.
0 computation of P and hP was done correctly.
In all the cases the program puts in array AP , P and hP , in position
0 and 2 respectively.

Unlike the point coord program of chapter 2 this function wont output any message to the
terminal if the height axis direction is null. This illustrates one way to deal with errors in function
by returning a special code. Here 1 code indicates an error in usage of pointcoord and the program
which calls this function has to handle this situation. Its not the function which has to do this
treatment. All what it does is to return if an error occurs or not. If another function calls your
pointcoord function, it may also postpone error treatment to the caller by also returning an error
code. And so on. This way of dealing with errors is rather common in C and C++. But C++
offers another more powerful mechanism called exception that we may encounter in the next labs.
Implement and compile the library (i.e. the file mathlib.cc) and test it with the main program
lib concept given in the file lib concept.cc. Whatever implementation you chose for those functions,
this program should give the appropriate results without modification of lib concept.cc source
6

file. Dont hesitate to take a look at lib concept.cc to check that you understand the way to use
pointcoord.
Requested information
Files

mathlib.cc,mathlib.h

Input
Output
Scaling : 2/16
Note : This is the first example of a requested information table with empty Input/Output
directive. This is normal since you have to use the teacher file lib concept.cc( and you are not
expected to change any thing in it) which does input/output. Auto evaluation tool is tuned to work
with lib concept.cc and your evaluation will be done here only on the results that your functions
give and not also on the way you present results (like in previous exercises). In the next labs you
will have many exercises like that.

First loops

Your program in both cases must use one of the loop structures available in C++ and use double
type for real arithmetic. You will use question 5 library to do the calculus. In particular for
both exercises you will consider a cylindrical coordinates system C defined by O(1., 1., 1.) and
D(0., 0., 1.)

6.1

First version

Write a program biggest 1 (stored in biggest 1.cc) that computes the biggest coordinate in C
(given above) of 3 points Pi i [1, 3] given by the user in a global Cartesian coordinate system R.
Input
Output

Requested program input/output


The program must ask three series of three real values to the user corresponding to Pi coordinates in R.
At the end of the input the program outputs the biggest coordinate in
C of the 3 entered points.

Requested information
Files
Input
Output

biggest 1.cc
xP1 , yP1 ,zP1 ,xP2 , yP2 ,zP2 ,xP3 , yP3 then zP3
BIGGEST(biggest )

Scaling : 1/16

6.2

Second version

Write a program biggest 2 (stored in biggest 2.cc) that computes the biggest coordinate in C
(given above) of points Pi given by the user in a global Cartesian coordinates system R.
Input
Output

Requested program input/output


The user enters Pi coordinates in R one point by one point. The program
will stop asking for new points if O coordinates are entered.
It must then output the number N of points entered (O point not
counted) and the biggest .
7

If the user starts by entering O point, the biggest is then set to -1 and as requested the
program stops asking for new points. It then outputs mandatory information and stops like with
any other input sequences.
Requested information
Files
Input
Output

biggest 2.cc
xPi , yPi ,zPi
INPUT(N ), BIGGEST(biggest )

Scaling : 1/16

computation

We want to compute without using trigonometric function. For that we will use the fact that :
Z

p
4 1 x2 dx =

(1)

To compute this integral your program will use a trapezoidal rule. This technique gives an
Z b
approximation of a defined integral
f (x) dx by approximating the area under the curve y = f (x)
a

by a trapezoid on the interval [a, b] :


Z


f (x) dx (b a)

f (a) + f (b)
2

Usually to obtain a better approximation [a, b] is divided into smaller intervals where the
trapezoidal rule is applied. This leads to the more generic formula with n uniform intervals :
!
Z b
k=n1
X
b a f (a) + f (b)
ba
f (x) dx
+
f (a + k
)
(2)
n
2
n
a
k=1

As a draft, write a program that computes the integral of (1) using the trapezoidal rule (2)
with a number of intervals n given by the user and outputs the result ( approximation) on screen.

Input
Output

Requested program input/output


n the number of intervals for the trapezoidal rule
The computed approximation

Check the result by outputting also the exact value of using for example arccos(1) (use
again cmath header).
When you are confident in your results, write the final program integ pi (stored in integ pi.cc
and using your working implementation ) which outputs the approximation error for different

computational result
number of intervals. The approximation error of the computation is : ref
ref
where ref is given by arccos(1.) and computational result by (2). This program is following
this new requirement :
Input
Output

Requested program input/output


m the maximum number of intervals used for trapezoidal rule.
Output the results on the screen by line, one corresponding to each
approximation of values following increasing number of interval up to
m. Each line has a token, a : and a value (see requested information
below for precise expected format).
8

Once you are satisfied with your results, copy them into a file (the column of error) along the
number of intervals and plot them using for example gnuplot or Libre Office. You should see
that for an increasing number of intervals, the error is reducing slowly. If you pass in loglog scale
for axes you get a straight line. If this is not what you get, check your implementation.
gnuplot is a small program to plot simple curves. It is widely available on linux platform. To
use gnuplot just type gnuplot in the command terminal. The plotting command is plot. Type
help plot to learn how to use it.
The following :
set logscale x
set logscale y
plot "integ_pi.res" using 1:2 title "pi error" with lines;
will plot the error curve coming from the text file integ pi.res which has 2 columns (the first one,
corresponding to the number of intervals, the second one to the results of your code)
Requested information
Files
Input
Output

integ pi.cc,
m
ERRi( error for i intervals )

Scaling : 4/16
Here is expected output :
ERR1 : 0.36338
ERR2 : 0.130361
ERR3 : 0.0713139
for m = 3
Optional : For those who are interested, you can generate another program based on integ pi
which uses Simpsons rule instead of trapezoidal rule. Normally you should observe a better error
convergence rate.

Annexe

8.1

Auto eval.bash limits

This tool is just a help to verify mainly that:


Your program is located in correct source files having correct names
No file is missing. If so you will be able to pass through all steps but your points for the
missing file will be lost.
Exercises program at least compiles and runs correctly (to obtain the 2 points see 8.2 ).
With the student parameter setting it gives correct results(to obtain the 6 points see 8.2 ).
The archive given to teacher has the correct structure and name.
What this tool doesnt verify is that:

Your programs are correct in absolute. Be careful auto eval.bash is tuned to have exercises
running with a set of parameter but different setting will be used by the teacher to correct your
work. This means that your code may work with auto eval.bash and the student parameter
setting but not with the teacher parameter setting. Its your responsibility to ensure that
your program is correct and work with any setting.
Your programs are correct if you just generate an archive and didnt pass through evaluation
step.
You give your correct group identification number. If you generated archive following a wrong
group ID and upload it as is you will have grade of zero for this homework.

8.2

Evaluation rule

The auto evaluation tool auto eval.bash will be used by teachers (in a slightly modified version)
to evaluate your work with the following rule:
For an exercise the mandatory program doesnt compile => 0 Points for the exercise.
For an exercise the mandatory program compiles but doesnt execute correctly (i.e. crash,stop
in the middle ...) => 1 Points
For an exercise the mandatory program compiles and executes without bug but doesnt give
correct results => 2 Points
For an exercise the mandatory program compiles, executes without bug and gives correct
results/behavior => 6 Points
Naturally when you are in position of having only 1 or 2 points, program will be inspected to see
if it is relevant (answering the question). If not (something that as nothing to do with the exercise
but compiles and runs correctly) => 0 points.
For every exercise an extra scaling is done. After each requested information table (see 8.4)
you will have the coefficient used for this scaling.
By using auto eval.bash you will be able to estimate how many source evaluation points you
will have for this lab without scaling.

8.3

Getting and using auto eval.bash

auto eval.bash like this pdf files come from self extracting file labX.bash that you download from
resource Lx subject in https://hippocampus.ec-nantes.fr Labs section of M SMA PROLA
course, where X correspond to current lab number.
Place auto eval.bash in the folder where you have all exercises source that have to be given to
teachers. Then in this folder just type:
> ./auto eval.bash
The first step is to input your group ID (letter A or B and a number):

Input your group letter and number

10

If you launch the script for the first time, you have to create an archive of your work. Select
Prepare an archive of your work.

Create archive
A .gz archive file is created, and ready to be uploaded on the pedagogic server. If you want, at
this point you can stop the program (Type q). Note that theses two steps at least are mandatory
to create the archive of your work that you will upload on the server. You can create this archive
by yourself (for instance using the tar command), but if there is any kind of problem when we
try to uncompress it, your grade may be affected with no protestation possible (the most stupid
problem would be that your archive doesnt have the correct name which leads to ... zero for the
wall lab evaluation) .
Otherwise, you can use this tool to get an auto-evaluation of your work. Now that your archive
is created, you can notice that a new command appeared, evaluate archive already generated.
Type b.

Auto-evaluate your work


Some information are displayed on the screen, saying that the auto-evaluation worked through
well (or not). The most interesting information for you are the ones on the next screen-shot.

11

Results of your auto-evaluation


Here you can see:
Which ones of your source codes compile correctly
Which ones of your programs run correctly
Which ones of your programs give the expected results
This way you can have an estimation of your grade according to the rules detailed in section
8.2. However keep in mind that the grade estimated using this tool may not be your definitive
grade (see section 8.1).Note that you can use this command only if you have generated an archive
first.
You could see that in the previous example, one of the results given by program ex1 is
incorrect. To display the difference between your results and the expected one, select the new
command display difference from solution of last generated archive by typing c.

12

Compare obtained results and expected results


Now you can:
Generate a new archive of your work, if you modified some of your source files
Auto-evaluate the current archive
Compare the results obtained with your program and the solution
Stop using the program
In the last case, if you decide to quit the program, you will be asked whether you want to clean
or save a certain temporary folder. This temporary folder was generated during the auto-evaluation
step, and can eventually be used for debugging even if the script is not launched. The ones of you
who are the most at ease with programming may want to use it, otherwise you can just delete it.

Stop the auto-evaluation program


13

8.4

Requested information

Table given at the end of each exercise untitled Requested information contains the following
items:
Files: This is the list of files which must be present in your archive uploaded in the server.
auto eval.bash harvest this files to generate the mandatory archive.
Input: This describes for each program the precise order in which informations must be
entered.
Output: This describes for each program the output format of results. Results (that
teacher want to check easily) must be presented by your program in a rather
rigid format described by followings:
A result is present on one single line. No other things may be written on that line.
A result is first identified by a token which starts the line.
After the token a : must separate token from result value.
After : result value must be written (it could be anything).
token, : and result value must be separated at least by one blank character.
In this section you have the list of mandatory results given by token names and in parentheses
by result name coming from subject.
Here is an example of a Lame program made of one file lame.cc. It is generating 2 output
results called and in the subject. From subject this program should ask for 2 input values call
E and to compute results. The requested informations table would look like
Requested information
Files
Input
Output

lam.cc
then E
MU(), LAMBDA()

Scaling : 1/8
Lame program execution would look like with E = 2500., = 0.28 and computed = 976.5625
and = 1242.8977 :
blablabla
please enter nu :
0.28
blabla
please enter E :
2500.
LAMBDA : 1242.8977
blabla
MU : 976.5625
blabla
Notice in this example that is asked before E as mandatory by Input directive. And and
appears in undefined order but with mandatory format (i.e token LAMBDA and MU).
Very important. You should avoid at any cost the use of token for anything else than the
result it corresponds. Consequences may result in a zero grade just because you messed up the
tools with false information.
In example above if in any blabla you write MU or LAMBDA you will get a zero for associated
results.
Last but not least when you enter information and output first a question message
14

you must always add a new line to your question if it precedes a result. Lets take
the example of Lame above which output token LAMBDA right after asking to input E. If
you dont follow this last recommendation you may ask for E without inserting new line after the
question as you can see in the example below:
Your executable is Lame and on terminal you type:
> ./Lame
And obtain the following bunch of output:
blabla
please enter E : 2500.
LAMBDA : 1242.8977
blabla
This works well on the terminal by typing on the keyboard 2500. and enter. But auto eval.bash
works differently. It uses what is called redirection mechanisms. And in fact this leads
auto eval.bash to miss recognize your results.
In this example you must add a end of line after the question to obtain:
> ./Lame
blabla
please enter E :
2500.
LAMBDA : 1242.8977
blabla
and auto eval.bash will work correctly in this case.

8.5

Useful

During Labs you will have questions where testing program ask for many inputs. During debugging
stage you may then be obliged to re enter those inputs manually many times. That may be error
prone and time consuming. To simplify your work use redirection.
For example lets take a prg program which run the following :
> prg
Enter number :
23
Enter number :
13
Enter number :
-1
Mean value :
18
Here for illustration we just limit inputs to three entries. Put all those inputs in a file, with one
input per line. Lets call this file ip.txt. Its contain for this example will be :
23
13
-1
Now if you type the following command you get the same execution of prg without typing
anything :
> prg < ip.txt
Enter number :
Enter number :
Enter number :
Mean value :
18
Note that inputs just vanish from terminal display.
15

Você também pode gostar