Solutions Exercises
Solutions Exercises
Solutions Exercises
Part I
1. Programming paradigms
(a) Yes, if you already possess a compiler or interpreter for that language. Only the first
compiler ever had to be written in machine code.
(b) Yes, that is possible.
(c) Yes it can, assuming that you have another compiler available to compile it for the first
time so you have an executable.
3. Names
Mathematical constants: e, π. Mathematical variables: x for something that varies, f for a
function, φ for an angle. Physical constants: the speed of light c, gravity constant g. Physical
variables: velocity v, acceleration a, mass m. If everyone uses the same symbols for certain
constants and variables, then it is much easier to communicate.
5. Comments
Comments can be written on a single line with the // notation, or spread over multiple lines by
starting the comment with /∗ and ending it with ∗/.
6. Concepts
An instruction is a programming construct that can be executed. A variable is a location in
memory with a name. A method is a group of instructions with a name. An object is a group
of variables that belong together. A class is a group of methods, and also the type of an object
that these methods can modify.
1
7. Declaration, instruction, expression
A declaration determines the type of a variable. An instruction can be executed, which will
change the memory. An expression can be calculated to determine its value.
9. Changing names
We have to change the name of the class, the name of the constructor method, and the call to
the constructor method from Main. It is not necessary to change the name of the .cs file, but in
general it is a good idea to assign the name of the class to the file in which it is defined.
The swap between x and y works for all cases. You can see that this works if you replace the
constants 40 and 12 by a and b. If you fill in these values on the right hand side the final
situation will be y = a, x = b. However, x and y shouldn’t be so big that x+y doesn’t fit into an
int anymore.
2
14. Hours, minutes, seconds
int hours = 0;
int minutes = 0;
int seconds = 0;
while (time >= 3600)
{
hours++;
time −= 3600;
}
while (time >= 60)
{
minutes++;
time −= 60;
}
seconds = time;
Or simpler:
int hours = time/3600;
int minutes = (time%3600)/60;
int seconds = time%60;
3
Part II
1. Keywords
The word ‘void’ means ‘empty’. We use this word to indicate that a method doesn’t have a
return value. The word ‘int’ is an abbreviation of integer, which is used to define the integer
type. The word ‘return’ is used in the body of a method to return a result, as well as return
the control of the program to the caller of the method. The word ‘this’ is used to indicate the
object that we’re currently manipulating. The ‘this’ reference is needed so that we can access
the variables stored in that object. We cannot use the ‘this’ word in a static method, since a
static method doesn’t manipulate an object.
2. Type conversions
x = (int)d;
x = int.Parse(s);
s = x.ToString();
s = d.ToString();
d = x; // no type conversion needed
d = double.Parse(s);
4
(f) string ManyTimes(string s, int nr)
{
string result = ””;
for (int i=0; i<nr; i++)
result += s;
return result;
}
4. Cuneiform
5. Sequences
5
res ∗= t;
return res;
}
(d) By reusing the Power and Factorial methods, we can write down this method as follows:
double Coshyp(double x)
{
double res; int t;
res=0;
for (t=0; t<40; t+=2)
res += this.Power(x,t)/this.Factorial(t);
return res;
}
This can be done slightly more efficiently by incorporating the factorial and power opera-
tions inside the method:
double Coshyp(double x)
{
double res, a, b; int s, t;
a=1; b=1; res=0;
for (t=0; t<40; t+=2)
{
res += a/b;
a ∗= x∗x;
b ∗= (t+1)∗(t+2);
}
return res;
}
6. Prime numbers
6
(d) bool Divisible(int x, int y)
{
return this.MultipleOf(x,y);
}
x 9
p q
Two Two
x 4 x 3
o o
One Two
x 8 x 2
o
The Two instance at the bottom right is greyed
out. Because it is no longer reachable through an object reference, it will be disposed of auto-
matically by C#’s garbage collection. You may therefore leave it out of the drawing.
9. Type checking
Types are checked during the compilation phase. You can store an object of a subclass in a
variable that has the type of a superclass:
7
class A {...}
class B : A {...}
class Test
{
static void Main()
{
A a;
B b;
With the cast you indicate as a programmer that you know because of the previous instructions
that the assignment is safe. During run-time there will be a final check to determine if the
variable a indeed contains an object of the subclass type. This check cannot be done at compile
time, since analysing where the object comes from is not always possible.
8
Part III
1. Arrays
2. string methods
9
{
c = this[n];
if (c==x)
c = y;
res += c;
}
return res;
}
3. Highway
(a) One declaration is still missing. Write down this declaration and indicate where it should
be placed in the program. In the class Highway, the following declaration should be added:
MotorizedVehicle[] road = new MotorizedVehicle[15];
(c) The element type of the array is MotorizedVehicle, so in the Draw method of Highway the
empty Draw method of the MotorizedVehicle class is called. This method should have been
declared as virtual and in the subclass as override.
(d) We run into version management problems. If the shape of the truck changes later on, the
code needs to be updated in two places.
(e) In the class Combination the trailer could have been drawn with the call base.Draw(g,x,y).
(f) Add a new class Wheel, independent of the other classes. Add a new class Vehicle as a
superclass of the MotorizedVehicle class. Within that class define an array of Wheel objects.
Add a new class Trailer as a subclass of Vehicle, and declare an instance of it in the Combination
class.
10
(a) double Largest(double [] a)
{
double result = a[0];
for (int t=1; t<a.Length; t++)
if (a[t] > result)
result = a[t];
return result;
}
11
(g) int First(int [] a, int x)
{
int low = 0;
int high = a.Length;
while (high>low)
{
int mid = (low+high)/2;
if (a[mid]==x)
return mid;
else if (a[mid]<x)
low = mid+1;
else high = mid;
}
return −1;
}
12
Part IV
1. Lists
2. Collections
13
(a) void Increment(IList<Counter> list)
{
for (int i=0; i<list.Count; i++)
list[i].Increment();
}
void Increment(IList<Counter> list)
{
foreach (Counter c in list)
c.Increment();
}
(b) We don’t have to change anything, because the class OwnList implements the IList interface.
As a result, all the properties and methods needed, such as the Count property and the
bracketed element access, are implemented.
5. Strings
A::Method1
A::Method2
A::Method1
B::Method2
B::Method1
B::Method2
7. Sidescrolling
14
position.X = MathHelper.Clamp(position.X, GraphicsDevice.Viewport.Width − background.Width, 0);
}
8. Decorator streams
public BufferedStream(Stream s)
{ subject = s;
count = 0; max=0;
}
You would think that the counter is incremented too soon, or not at all because we already
return from the method. This is not the case, it works exactly as you would hope: the old value
of count is used to index the array, and then the value of count is incremented. If we used the
expression ++count instead, the counter would be incremented before indexing the array, but of
course in this case it is not what we want.
15
Part V
1. Text files and collections
while ((line=input.readLine())!=null)
foreach (string word in line.Split(” ”))
everything.Add(word);
foreach (string t in everything)
output.writeLine(t);
}
catch (Exception e)
{ Console.WriteLine(”An error occured.”);
}
}
}
}
3. Tetris blocks
16
bool tmp = block[x, y];
block[x, y] = block[block.GetLength(0) − 1 − x, y];
block[block.GetLength(0) − 1 − x, y] = tmp;
}
}
}
Instead of using the if instruction inside the for loop, you could have also used the ToString
method of the boolean type. The method would then be given as follows:
public void Print(bool[,] array)
{
for (int y = 0; y < array.GetLength(1); y++)
{
for (int x = 0; x < array.GetLength(0); x++)
Console.Write(array[x,y].ToString() + ” ”);
Console.WriteLine();
}
}
4. Abstract classes
17