REC06+Problems+Set+Solutions

REC06+Problems+Set+Solutions - 14:440:127- Introduction to...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 14:440:127- Introduction to Computers for Engineers Problems for students to attempt in Recitation 6- Solutions 1) Write a for loop that calculates 20! (20 factorial). You may not use the factorial( ) function. total=1; for x=1:20 % or 20:-1:1 total=total*x; end disp(total) 2) Write a while loop that continually asks the user to input a number. Each time he/she enters a positive number, you should display that number to the screen. Once the enter a number thats not positive, the loop should stop, and you should display Loop Stopped to the screen. x=input( 'Enter a number' ); while (x>0) disp(x) x=input( 'Enter a number' ); end disp( 'Loop stopped' ) 3) Write a for loop that calculates the sum of the prime numbers from 1 to 1000. total=0; for x=1:1000 if (isprime(x)) total=total+x; end end disp(total) % without loops: sum(primes(1000)) 4) Write a while loop that finds the smallest 8 digit prime number. Then, instead write that loop as a for loop (using the break command). n=10000000; % smallest 8 digit number while (~isprime(n)) % loop until you find a prime n=n+1; end disp(n) for n=10000000:99999999 if (isprime(n)) break end end disp(n) 5) Use the following command to create a 10x10 matrix: C = round(500*rand(10)); Write a nested for loop that finds the maximum value in that matrix. C = round(500*rand(10)) z=size(C); maxval=-inf; for r=1:z(1) % z(1) is the number of rows in C for c=1:z(2) if (C(r,c)>maxval) maxval=C(r,c); % set maxval = to current number end end end disp(maxval) % to write this without a nested loop C = round(500*rand(10)) Cvector = C(:); % turn C into a vector maxval=-inf; for e=1:length(Cvector) if (Cvector(e)>maxval) maxval=Cvector(e); end end disp(maxval) 6) Write a loop that creates the following matrix. Notice that the first row is 1*[4 8 12], the second row is 2*[4 8 12], the third row 3*[4 8 12], etc....
View Full Document

Page1 / 7

REC06+Problems+Set+Solutions - 14:440:127- Introduction to...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online