Recitation 6 Problems- Solutions

Recitation 6 - 14:440:127 Introduction to Computers for Engineers Problems for students to attempt in Recitation 6 Solutions 1 Write a for loop

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

View Full Document Right Arrow Icon
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 that’s 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);
Background image of page 1

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

View Full DocumentRight Arrow Icon
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(:);
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/29/2012 for the course 440 127 taught by Professor Blase during the Fall '09 term at Rutgers.

Page1 / 6

Recitation 6 - 14:440:127 Introduction to Computers for Engineers Problems for students to attempt in Recitation 6 Solutions 1 Write a for loop

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