CS 99

Summer 2002                                                                                       7.18

 

Sample Prelim 2 Questions

 



1.       The n-th Fibonacci number is defined by the following recursive equations:

f( 1 ) = 1
f( 2 ) = 2
f( n ) = f( n – 1 ) + f( n – 2 )

Therefore, f( 3 ) = f( 2 ) + f( 1 ) = 2 + 1 = 3, and so forth for higher numbers.   Write a program to calculate and write out the n-th Fibonacci number for n > 2, where n is input by the user.  Use a while loop to perform the calculation.


2.       Write a program that converts a 1-D array into a 2-D array with the 1-D array on the diagonal and “reverse diagonal”. For example,

[1 2 3]

becomes

[1 0 3]
[0 2 0]
[1 0 3]


3.       Write a program which computes the cumulative products of the elements in a vector x and stores them in another vector p.  The j-th element of vector p will be

 p( j ) = x( 1 ) * x( 2 ) * ... x( j ).


4.       What MATLAB command would you use to compute the sum 1 + 4 + 7 + … + 100?

5.       Write a program that asks for an integer n  and then computes the following:

While the value of n is greater than 1, replace the integer with half of its value if the integer is even (n/2); otherwise, replace the integer with three times its value plus 1 (3*n + 1).


6.       Given x = [3 1 5 7 9 2 6], explain what the following commands “mean” by providing the result of the command.

A.      x( 3 )
B.       x( 1:7 )
C.             x(1:end)
D.      x(1:end-1)
E.             x(6:-2:1)
F.       x([1 6 2 1 1])

7.       Given the array x from problem 5 above, provide the command that will

A.      assign the even-numbered columns of x to an array called B
B.       assign the odd-numbered rows to an array called C
C.       compute the reciprocal of each element of x
D.      compute the square-root of each element of x

8.       p = 5;
d = 0;
n = 0;
while p > 1
    d = 2;
    while  mod( p, d ) ~= 0

     d = d + 1;
     end
     if d == p

     n = n + 1;
     end

          p = p - 1;
     end

 

 

p:

5

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

d:

 

0

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

n:

 

 

0