CS 99

Summer 2002                                                                               7.22

Solutions to Sample Prelim 2 questions

1.       n = input(‘Enter a number greater than 2: ‘);
while n < 2
    n = input(‘er … greater than 2: ‘);
 end
flast = 1;
fnext = 2;
count = 2;
while count <= n
    tmp = fnext;
    fnext = fnext + flast;
    flast = tmp;
    count = count + 1;
end
if mod( n , 10 ) == 1
    suff = ‘st’;
elseif mod(n, 10 ) == 2
    suff = ‘nd’;
elseif mod(n, 10 ) == 3
    suff = ‘rd’;
else
    suff = ‘th’;
end
fprintf(‘The %d%s fibonacci number is %d’, suff, flast );

2.       a=input('Enter a 1-D array: ');
[rows,cols]=size(a);
A=zeros(cols);
rows=cols;
 %for each row
 for i=1:rows
    % for each column
    for j=1:cols
        %1D array on the diagonal
        A(i,i)=a(i);
        %"reverse diagonal"
        A(i,cols-i+1)=a(cols-i+1);
    end
end
A


3.       Solution 1.
p = zeros( 1, length( x ) );
for ii = 1 : length( x )
    p( ii ) = prod( x( 1: ii ) );
end


Solution 2.
p = ones( 1, length( x ) );
for ii = 1 : length( x )
    for jj = 1 : ii
         p( ii ) = p( ii )*x( jj );
    end
end

4.       sum( 1 : 3 : 100)

5.       n = input(‘Enter an integer: ‘);
while n > 1
    if mod( n, 2 )
        n = 3*n + 1;
    else
        n = n/2;
    end
end
 

6.       A.      x( 3 )                                    %5                             (3rd element of x )
B.      
x( 1 : 7 )                               %[3 1 5 7 9 2 6]             (elements 1 through 7 of x)
C.      
x( 1 : end )                           %[3 1 5 7 9 2 6]             (elements 1 through to the end of x)
D.     
x( 1 : end-1 )                         %[3 1 5 7 9 2]                 (elements 1 through 6 of x)
E.      
x( 6 : -2 : 1 )                         %[2 7 1]                            (elements 6, 4, 2 of x, in that order)
F.      
x( [1 6 2 1 1] )                       %[3 2 1 3 3]                     (elements 1, 6, 2, 1, 1 in that order)

7.       A.      B = x( 2 : 2 : end )
B.      
C = x( 1 : 2 : end )
C.      
1./x
D.      sqrt( 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

 

 

 

 

 

 

 

4

 

3

 

 

 

2

 

 

1

d:

 

0

 

2

3

4

5

 

 

2

 

2

3

 

 

2

 

 

n:

 

 

0

 

 

 

 

1

 

 

 

 

 

2

 

 

3