INF205 lab worksheet 1

1. Basic tools

  1. Make sure that the system that you are using has a functioning C++ compiler, such as GCC. Use it to compile a simple C/C++ code.
  2. Make sure that GNU make is installed on your system. Use GNU make to compile code that contains multiple code files.
  3. Try out an IDE that is suitable for C++, for example Eclipse. Use it for a program that contains multiple code files.

2. From C++ to Python

Translate the following code to Python:

double scalar_product(double x[], double y[], double dimension)
{
    double sum = 0.0;
    for(int i = 0; i < dimension; i++) sum += x[i]*y[i];
    return sum;
}

3. From Python to C++

Rewrite in C++. Note that like in every complete C/C++ code, there will need to be a int main() function.

# output Fibonacci numbers smaller or equal to x
# return True if x is a Fibonacci number, False if it is not
#
def print_fibo_until(x):
    n = 1
    fibo_n = 1
    fibo_previous = 0
    
    while x >= fibo_n:
        print(n, fibo_n, sep="\t", end="\n")
        
        fibo_next = fibo_n + fibo_previous
        
        n += 1
        fibo_previous = fibo_n
        fibo_n = fibo_next
    return x == fibo_previous
    
y = 17711
if print_fibo_until(y):
    print(y, "is a Fibonacci number")
else:
    print(y, "is not a Fibonacci number")

4. Size of the primary data types, in bytes

Use the keyword sizeof to determine, for your system, what size the following data types have: bool, char, short, int, long, and long long; float, double, and long double.

5. Using C/C++ arrays

Write a function that normalizes a three-dimensional vector, converting it into the unit vector pointing in the same direction. The vector should be passed as a double array, i.e., as a static array of double-precision floating-point values.

6. Program analysis - termination of a recursive function

Under what conditions does the following function terminate and return a value?

bool f(unsigned n)
{
    if(n == 'x') return true;
    else return f(n - 256);
}

Replace this code by a simple one that always terminates, returns true where the given f(n) returns true, and returns false where the given f(n) does not terminate.

7. Program analysis - return value of a function

Analysing the following code, determine the return value of f(n) as a function of n, proving by induction that this is how the code behaves.

long f(int n)
{
    if(n == 0) return 0;
    else if(n < 0) return -f(-n);
    else return f(n-1) + 3*n*(n-1);
}

Write a code that is equivalent to the one given above, but more computationally efficient.

(submit through Canvas by end of 13th February 2024)

Index