CS 1112 Exercise 3: Iteration with for-loops

Due date: Sunday, February 28, 11:00pm EST.

The exercise must be submitted on CMS (Exercise 3).

Remember to keep your files organized! Start a directory (folder) for this exercise, Ex3. When downloading a file, do a right-click (Windows) or ctrl-click (Mac) on the file name and select save link as to control exactly where your file will go!

Review Ex 2

Look closely at your scripts angle1, angle2, and angle3. Are your Boolean expressions as concise as they can be? These three scripts are being graded for completeness only, not correctness, so be sure to talk with classmates and/or course staff if you have any uncertainties about your solutions.

Multiples of k

This is a discussion question—no submission required—so discuss and compare your answer with your classmates before the end of the class!

The following program should read an integer k and output all positive multiples of k up to and including 1000. Fill in the blank.

k = input('Please enter a positive integer smaller than 1000: ');

for j = ______________________
     fprintf('%d ', j)
end
fprintf('\n')

Approximate square root (again!)

The square root of a positive value A can be computed by building “increasingly square” rectangles with area A (see notes from Lecture 1). Write a script approxSqrt to solicit a positive value A and a positive integer N. Then compute A\sqrt{A} by building N increasingly square rectangles. Let the first rectangle have length A and width 1. The final square root value is the average of the length and width of the Nth rectangle. Display neatly the length and width of all the rectangles and the final estimated value of the square root.

Do not use arrays, i.e., you will use scalar variables L and W for the length and width of a rectangle, respectively.

Approximate π

[Modified from Insight Exercise P2.1.5]

For large n,

Tn=1+122++1n2=k=1n1k2π26Rn=113++(1)n+12n1=k=1n(1)k+12k1π4\begin{aligned} T_n &= 1 + \frac{1}{2^2} + \cdots + \frac{1}{n^2} = \sum_{k=1}^n \frac{1}{k^2} &\approx \frac{\pi^2}{6} \\ R_n &= 1 - \frac{1}{3} + \cdots + \frac{(-1)^{n+1}}{2n-1} = \sum_{k=1}^n \frac{(-1)^{k+1}}{2k-1} &\approx \frac{\pi}{4} \end{aligned}

giving two different ways to estimate π:

τn=6Tnρn=4Rn\begin{aligned} \tau_n &= \sqrt{6 T_n} \\ \rho_n &= 4 R_n \end{aligned}

Write a script approxPiSeries that displays the value of |πρn||\pi-\rho_n| and |πτn||\pi-\tau_n| for n = 100, 200, …, 1000 in one table. Do not use arrays.

Submit your files approxSqrt.m and approxPiSeries.m on CMS.