Recitation 9 Problems- Solutions

# Recitation 9 Problems- Solutions - 14:440:127- Introduction...

This preview shows pages 1–3. Sign up to view the full content.

14:440:127- Introduction to Computers for Engineers Problems for students to attempt in Recitation 9. SOLUTIONS 1) Write a function called “dice” that simulates the throw of two dice by returning a vector containing 2 random integers between 1 and 6. function v = dice( ) v = ceil(6*rand(1,2)); 2) Write a function that outputs the 9th prime number in a vector. The vector is 121:1:4343. You cannot use the primes( ) function, although you certainly may use the isprime( ) function. Save the following as output9th.m function ninth = output9th(v) ninth=-inf; count=0; x=0; while x=x+1; if (isprime(v(x))) count=count+1; end end if (count==9) ninth=v(x); end Then type the following in the workspace: v = 121:1:4343; output9th(v) 3) Write down the basic structure of 'for' and 'while' loop. (You don't need specify variable names). What are the major differences between the two methods? for VARIABLE = VECTOR STATEMENTS end while(CONDITION) STATEMENTS end For specifies exactly how many times it will loop, whereas while loops while the condition continues to be true. 4) Use for loop and the following formula to calculate π /4: s=0; for n=1:10000 s = s+1/(4*n-3) - 1/(4*n-1); end disp(s)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document