CS 99

Summer 2002: HW 7                                                                        07.17

Solutions

1.    Tracing
n = 57;
x = 0;
y = 1;
while n ~= 0
    if mod( n, 2 ) ~= 0
        n = floor(n/3);
    else
        n = n + 1;
        x = x*9;
        y = y + 10;
    end
end

n:

57

 

 

19

6

7

 

 

2

3

 

 

1

0

x:

 

0

 

 

 

 

0

 

 

 

0

 

 

 

y:

 

 

1

 

 

 

 

11

 

 

 

21

 

 


   
Write your answers in the table supplied (or a reasonable facsimile) and include it with your other documents.

2.    Star Patterns
In the program segments below, you may only use loops, branches, and the following types of fprintf statements:

·         fprintf(‘\n’)

·         fprintf(‘*’) or fprintf(‘’\\’) or fprintf(‘/’)

·         fprintf(‘  ‘)      % use two spaces instead of one: things won’t line up properly otherwise



A)     
n = input(‘Enter a positive number: ‘);
          
for rows = 1 : n
             for cols = 1 : (n – rows + 1)
                 fprintf(‘*’);
            end
             fprintf(‘\n’);
        end


B)     
n = input(‘Enter a positive number: ‘);
          
for rows = 1 : n
             for cols = 1 : n
                 if rows == 1 | cols == 1 | cols == n | rows == n
                      fprintf(‘*’);
                 else
                      fprintf(‘  ‘);
                 end
            end
             fprintf(‘\n’);
        end


C)    n = input(‘Enter a positive number: ‘);
          
for rows = 1 : n
             for cols = 1 : n
                 if rows == 1 | cols == 1 | rows == cols | cols == n | rows == n
                      fprintf(‘*’);
                 else
                      fprintf(‘  ‘);
                 end
            end
             fprintf(‘\n’);
        end



D)      n = input(‘Enter a positive number: ‘);
          
for rows = 1 : n
            %print leading spaces
             for cols = 1 : n – rows + 1
                 fprintf(‘  ‘);
            end
            %print odd number of stars
             for cols = 1 : (2*rows – 1)
                 fprintf(‘*’);
            end
             fprintf(‘\n’);
        end



E)*     n = input(‘Enter a positive number: ‘);
        for rows = 1 : 2*n
             for cols = 1 : 2*n
                 if cols == n – row + 1 | cols == 3*n – row + 1
                      fprintf(‘/’);
                 elseif cols == n + row | col == row – n
                      fprintf(‘\\’);
                 else

                      fprintf(‘  ‘);
                 end

            end            
             fprintf(‘\n’);
        end