Вы находитесь на странице: 1из 2

MTS 3023: DATA STRUCTURES

SEMESTER 2 SESI 2017/2018


ASSIGNMENT 1

Answer ALL of the questions below:

1. Given the declaration:

int x;
int *p;
int *q;

Evaluate the following statements as valid or invalid. If the


statement is invalid, please explain why.

a. p = q;
b. *p = 56;
c. p = x;
d. *p = *q;
e. q = &x;
f. *p =q;

2. What is the output of the following code?

int *p;
int *q;
int i;

p = new int[5];
p[0] = 5;

for (i = 1; i < 5; i++)


p[i] = p[i – 1] + 2 * i;

cout<< “Array p: “;
for (i = 0; i < 5; i++)
cout<< p[i] <<” “;
cout<< endl;

q = new int[5];

for (i = 1; i < 5; i++)


q[i] = p[4 – i];

cout<< “Array q: “;
for (i = 0; i < 5; i++)
cout<< q[i] <<” “;
cout<< endl;
3. Please compare the algorithm below:

Algorithm 1
1. for i= 0 to i = 4
1.1 get the num[i]
1.2 sum = sum + num[i]
2. Average = sum / 5
3. Print sum
4. Print average

Algorithm 2
1. for i= 0 to i = 4
1.1. get the num[i]
2. for i= 0 to i = 4
2.1 sum = sum + num[i]
3. Average = sum / 5
4. Print sum
5. Print average

Calculate the complexity of the algorithm. Choose the most


efficient algorithm, explain your choice.

3. Given two integers x and y, the following recursive definition


determines the greatest common divisor (gcd) of x and y, gcd(x,
y):

x if y = 0
gcd(x, y) = gcd(y, x % y) if y ≠ 0

Write the program to test this fuction. What is the value of:

a. gcd(54, 24)
b. gcd(5, 38)

Please trace your answers.

Due date: Week 7

Вам также может понравиться