Testing and Debugging


Motivating question: how do you know if your code works correctly?

Kinds of errors

 

 

Debugging techniques

 

 


Code tracing:

What is displayed in the Command Window when each of the following code fragments is executed? If the code has an error, how would you fix it?

Code fragment 1

abc = 3;

for k = 1:5
    abc(k) = abc(k-1*k;
end

disp(abc)

Code fragment 2

a = 5;
k = 0;

while k < 4
    a = a + k;
    
    if mod(a, 4) == 0
        disp('zero')
        
    if mod(a, 4) == 1
        disp('one')
        
    if mod(a, 4) == 2
        disp('two')
        
    else 
        disp('three')
    end
    
    k = k + 1;
end

Code fragment 3

abc = 3;
bca = 3;

for i = [ 3 5 2 ]

    abc = [ abc   abc(length(abc))/i ];
    bca = [ bca(1)/i   bca ];
    
end

disp(abc)
disp(bca)

 

 

 

 

 

 


Code writing: input validation

Write a program to get an employee ID and a password from a user. First, the program should repeatedly prompt the user for an ID until the user enters a valid ID. Then the program should repeatedly prompt the user for a password until the user enters a valid password.

An ID is valid if it is a 7 digit number (and the first digit can't be 0).

A password is valid if it meets the following two criteria:

  1. it is at least 6 but no more than 10 characters long
  2. the first character is a letter or an underscore