Mts 3023: Data Structures SEMESTER 1 SESI 2018/2019 Assignment 1
Mts 3023: Data Structures SEMESTER 1 SESI 2018/2019 Assignment 1
a. p = q;
Valid, because two pointers can be equated.
b. *p = 56;
Invalid, because need to have another variable to declare
and put ‘&’ before the variable. In this case, x already
been declared as integer. So the valid one is p=&x,
*p=56;
c. p = x;
Invalid, because need to put ‘&’ before x and cannot
declare the pointer only by null.
d. *p = *q;
Invalid, because p and q are not connected with the
address.
e. q = &x;
Valid, because x already be declared and already put ‘&’
before x.
f. *p =q;
Invalid, because of the use of the * on p.
1
2. What is the output of the following code?
int *p;
int *q;
int i;
p = new int[5];
p[0] = 5;
cout<< “Array p: “;
for (i = 0; i < 5; i++)
cout<< p[i] <<” “;
cout<< endl;
q = new int[5];
cout<< “Array q: “;
for (i = 0; i < 5; i++)
cout<< q[i] <<” “;
cout<< endl;
Array p: 5 7 11 17 25
Array q: 17 11 7 5
2
The operation is:
p[0] =5 q[i]=p[4-i]
q[1]=p[4-1]
p[1] = p[1-1] + 2*i =p[3]
=p[0]+2 =17
=5+2
=7 q[2]=p[4-2]
=p[2]
p[2] =p[2-1] + 2*2 =11
=p[1]+4
=7+4 q[3]=p[4-3]
=11 =p[1]
=7
p[3] =p[3-1] + 2*3
=p[2]+6 q[4]=p[4-4]
=11+6 =p[0]
=17 =5
p[4] =p[4-1] + 2*4
=p[3]+8
=17+8
=25
3
3. Please compare the algorithm below:
Algorithm 1 Algorithm 2
1. for i= 0 to i = 4
1. for i= 0 to i = 4 1.1 get the num[i]
1.1 get the num[i] 2. for i= 0 to i = 4
1.2 sum = sum + num[i] 2.1 sum = sum + num[i]
2. Average = sum / 5 3. Average = sum / 5
3. Print sum 4. Print sum
4. Print average 5. Print average
Calculate the complexity of the algorithm. Choose the most efficient algorithm,
explain your choice.
4
4. 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
a. gcd(54, 24)
b. gcd(5, 38)
Answer:
a) gcd(54, 24) b) gcd(5, 38)
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int gcd(int x, int y);
{ int gcd(int x, int y);
if (y == 0) {
{ if (y == 0)
return x; {
} return x;
else }
{ else
return gcd(y, x % y); {
} return gcd(y, x % y);
} }
}
int main()
{ int main()
int x=54; {
int y=24; int x=5;
int y=38;
cout << "GCD is: " << gcd(x,y) <<
endl; cout << "GCD is: " << gcd(x,y) <<
return 0; endl;
} return 0;
}
5
The way to trace the answer:
24)542 5)387
- 48 - 35
----------- ---------
6)244 3)51
-24 -3
------ ----
0 now the remainder is zero. So 2)31
we need to stop here. -2
The value of gcd(54, 24) is 6. ---
1)22
-2
----
0 now the remainder is zero. So
we need to stop here.
The value of gcd(5,38) is 1