cs109: Programming Paradigms – C++ FS 2015

¨ BASEL
UNIVERSITAT
Thorsten M¨
oller
Alexander Haesen
Mihai Rapcea
cs109: Programming Paradigms – C++
Exercise 1
FS 2015
Deadline: 29.03.2015 23:59:59
Note: Please upload answers to the questions and source code before the
deadline via courses.cs.unibas.ch. Running programs have to be demonstrated
during the exercise slot on 30.03.2015 or 10.04.2015.
Modalities of work: The exercise can be done in groups of at most 2 persons.
Do not forget to provide the full name of all group members together with the
submitted solution.
Question 1: Declarations & Definitions
(9 points)
a) Consider the following lines:
double d1 = 3 . 1 4 1 5 9 2 6 5 ;
extern double d2 ;
d1 = d2 ;
Are these definitions, declarations, a combination of both, or neither a definition nor
a declaration? Explain.
b) Given the following code, up to which line would it compile without errors? Why?
1
2
3
4
5
6
bool f o o ( int x=−1, int y=−1);
bool f o o ( int x , int y ) { return x < y ; }
double bar ( double x ) ;
double bar ( double x ) { return x ∗ x ; }
double bar ( double x ) ;
f l o a t bar ( double x ) ;
Question 2: Function Prototypes
(5 points)
Define the prototype for the following functions. Parameter names may be freely chosen
if not specified. Choose types that are appropriate in the specified context.
a) A function named pow that calculates the power of two double values provided as
parameters.
1
b) A function named isLeapDay that has the year, month, and day as parameters and
returns whether the parameters correspond to a leap day or not.
c) A function named freeMem that prints the amount of free memory to the standard
output stream.
d) A function named setDebugInfo that sets a static message to the given value.
e) A function named divide that returns a division of two parameters and that defaults
the denominator to a non-zero value.
Question 3: Input & Output
(8 points)
a) Write a C++ program, that asks the user for a word and determines if this word is a
palindrome or not. A palindrome is a word which reads the same forward or backward
(e.g. kayak ). If the entered word is a palindrome, determine if it is a palindrome with
middle (e.g. radar ) or without (e.g. noon).
Hints:
• Include <string>
• The string-class provides functions like str.length() or str.at(int i)
b) Write a C++ program, that first asks the user for a word, then for a letter or enter.
The program then constructs a palindrome with these two inputs by combining the
word, the letter if given, and the reverse of the word.
Make sure that the second input is only one character (e.g., if the length is more than
one, ask the user again to enter a letter or enter).
Examples:
• word: le, letter: v, output: level
• word: ab, letter: enter, output: abba
Hints:
• cin << waits for formatted input, to capture a letter or enter, use getline()
• To reverse a word, use the reverse() function. It takes two iterators as input,
the initial and final positions of the sequence to be reversed. You can get these
by calling begin() or end() on a string.
Question 4: Structures and sizeof Operator
(6 points)
The instruction in the first line of the C/C++ source code listed below is an advanced
feature that can be used to adjust the memory alignment of data. Provided that the
hardware supports non-aligned memory access (i.e., an access of an address that is not a
multiple of the architecture’s word size), which is the case for x86 architectures, one can,
for instance, instruct the compiler to use a one-byte alignment (which is precisely what
is done in the source code).
2
#pragma pack ( 1 )
struct f o o {
bool b1 ;
int i ;
bool b2 ;
long l ;
};
a) First, explain what kind of instruction it is. Second, given the foo structure, if one
would compile with a one-byte, a four-byte, and an eight-byte alignment (#pragma
pack(1), #pragma pack(4), or #pragma pack(8), respectively), the sizeof operator
would return 14, 20, and 24 bytes, respectively, on a 64 bit x86 architecture (verify
this on such an architecture). Explain the different results! What tradeoff is being
made between the different settings?
b) Is the foo structure optimally designed in terms of memory consumption regarding
a four and eight-byte alignment? If not, find an optimal layout.
Question 5: Enumerations
(5 points)
Given the structure and enumeration below, write a C++ program that does the following: The users enters a numbers first. If the number is either 2 or 4, it is assigned to the
nbWheels field of a newly created Vehicle; otherwise an error message is printed and the
program terminates with a return value −1. If n is 2 then the t field is initialized with
BIKE; otherwise it is initialized with CAR. Afterwards, the program prints out what
kind of vehicle the user drives.
enum VehicleType {
BIKE ,
CAR
};
struct V e h i c l e {
int nbWheels ;
VehicleType t ;
};
Question 6: Mandelbrot
(12 points)
Implement a C++ program that computes the Mandelbrot set 1 over a range of complex
numbers by printing membership for each complex number on the console, which will
result in an ASCII art pattern – a fractal – as shown in Figure 1.
The Mandelbrot set is defined as the set of complex numbers c ∈ C, for which the sequence
z0 = 0, zn+1 = zn2 + c (also called the orbit of 0) remains bounded. More formally, the
Mandelbrot set consists of the complex numbers for which there is a constant k, such
that all terms of the sequence are smaller than k.
M = {c | ∃k∀n : zn < k, z0 = 0, zn+1 = zn2 + c} .
1
http://de.wikipedia.org/wiki/Mandelbrot-Menge
3
.................................................................................
........................................*........................................
........................................*........................................
........................................*........................................
........................................*........................................
........................................*........................................
........................................*........................................
.......................................***.......................................
.....................................*******.....................................
....................................*********....................................
..................................*************..................................
....................................*********....................................
.....................................*******.....................................
.................................*.***********.*.................................
................................*****************................................
............................*************************............................
...........................***************************...........................
...........................***************************...........................
........................*********************************........................
.......................***********************************.......................
.........................*..*************************..*.........................
............................*************************............................
.............................***********************.............................
.............................***********.***********.............................
.................................*..**.....**..*.................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
.................................................................................
Figure 1: Mandelbrot Set
4
By coloring the points in the complex plane belonging to the set, the Mandelbrot set can
be visualized.
To implement the abovementioned equation for a complex number c, one would have to
consider all terms of the sequence zn , which is impossible in practice. We will thus consider
a complex number belonging to the Mandelbrot set if, after a certain number of iterations,
the orbit remains bounded regarding the absolute value |zi | (0 ≤ i ≤ n) or escapes (i.e.,
goes to infinity). If the orbit for some c escapes, it does so quickly. Therefore, a value of
n = 25 is sufficiently large for testing whether c is within or outside the Mandelbrot Set.2
For each x, y point in the area to be displayed (corresponding to the c in the equation,
c = x + yi), the orbit is determined starting from z0 = 0. If the orbit escapes, “.” is
printed on the console. Otherwise, “*” is printed.3 Use −2 ≤ x ≤ 2 with a step size of
0.05 and −2 ≤ y ≤ 2 with a step size of 0.1 as the display area range. This, in turn, has
the consequence that the set membership criterion changes to limn→∞ |zn | ≤ 2.
p
To calculate the absolute value of a complex number (|x + yi| = x2 + y 2 ), you can
inculde math.h and use the sqrt function.
Finally, you might want to use the following structure for representing a complex number:
struct Complex {
float re ;
f l o a t im ;
};
Question 7: Recursive Function4
(0 points)
Implement a C++ function that calculates the difference of the first n positive “cubed”
numbers and returns the result as an integer. This difference is formally expressed as
follows
n3 − . . . − 23 − 13 .
The function should take n as a parameter of type unsigned int and return the result
as an int. The method should furthermore not have any local variables other than formal
parameters. Make sure to test the implementation; e.g., the result for n = 10 is −1025.
There are two undesired phenomena that can occur at runtime. Which are these phenomena? Find values for n (analytically or experimentally) for which the phenomena occur.
What could be done to prevent/handle them (i.e., to make the implementation more
robust)?
2
A larger value for n is useful if one wants to work with many different colors to generate nice looking
fractals.
3
In our simple ASCII art variant, these two symbols represent what are usually colors.
4
Optional task. There is no need to solve this task nor is it graded if done.
5