90 likes | 181 Views
COMP 116: Introduction to Scientific Programming . Lecture 16: Programming lab : While loops. 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.
E N D
COMP 116: Introduction to Scientific Programming Lecture 16: Programming lab: While loops
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
While loop example : Cumulative sum % A is pre-assigned 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 I: 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 I: 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? • Matlab commands you would need: input
Exercise II: Inside the square • Write a script using if-else-elseif-end that • Plots a square (plot, xlim, ylim) • Allows the user to click (ginput) on the figure window • If the user clicks inside the square display (disp, title) ‘inside’, otherwise display ‘outside’ • Write an infinite while loop that allows the user to click over and over again.
Exercise III: Golden ratio • Golden ratio is the “second-most famous irrational number” – New York Times 3 days ago . It is also the solution of • Guess a positive number x and repeatedly run the command x=sqrt(x+1) • The value of x will converge to the golden ratio 1.61803389975 • Now use while loops to find a number x such that • This x would be a good approximation of the golden ratio