100 likes | 236 Views
COMP 116: Introduction to Scientific Programming . Lecture 15: While Loops. Recap. What we’ve learnt so far: MATLAB stuff Matrices, vectors, indexing, matrix manipulation Programming stuff Conditional statements (if-else-end). If-else-end.
E N D
COMP 116: Introduction to Scientific Programming Lecture 15: While Loops
Recap What we’ve learnt so far: • MATLAB stuff • Matrices, vectors, indexing, matrix manipulation • Programming stuff • Conditional statements (if-else-end)
If-else-end • Interpreted as: If the logical expression <test> evaluates to true execute commands1, otherwise execute commands2 if <test> commands1; % True else commands2; % False end
Display absolute value % Implement our own absolute value % inVal = |inVal| % inVal should already be assigned % Is input value negative ? if (inVal < 0) % Parenthesis optional outVal = -inVal; % Invert negative else outVal = inVal; % Keep positive end disp(outVal);
Loops • When you want to do something over and over again • Interpreted as: • Evaluate <test> • If true run commands1 • Go to step 1 while <test> % Called the loop condition commands1; % Called the body of the loop end
What does this code do? % Assume A is a pre-assigned vector i=1; B=zeros(size(A)); while i<=length(A) B(i)=A(i)*2; i=i+1; end • Does this code terminate? • What is the value of i when the code terminates? • Upload answers using the link on the lecture page
What does this code do? % Assume A is a pre-assigned vector i=1; var=0; while i<=length(A) var=var+A(i); i=i+1; end • Does this code terminate? • What is the value of i when the code terminates? • What is the value of var when the code terminates?
Exercise I: Cumulative sum • Given a vector A, write a script that computes the cumulative sum of A i.e. A vector B, such that • Use cumsum(A) to get an idea B=zeros(size(A)); B(1)=A(1); i=2; while i<=length(A) B(i)=B(i-1)+A(i); i=i+1; end
Exercise II: Guess the secret number % Define a secret number between 0 and 20, make % the user guess it secret = 7; guess = input(“Guess the number: ”); -- if the guess is less than secret-- disp(`low'); -- if the guess is greater than secret-- disp(`high.'); -- otherwise -- disp(num_guesses);
Exercise II: Guess the secret number secret=ceil(20*rand); curr_guess=input(‘Guess: ‘); num_guesses=1; while (curr_guess ~= secret) if (curr_guess > secret) disp(‘high’); else disp(‘low’); end curr_guess=input(‘Guess: ‘); num_guesses=num_guesses+1; end disp(num_guesses); • Implement the guess-the-secret-number game using while loops and if-else-end. Count how many guesses the user needs • What should be the loop condition? • What should happen inside the loop body?