Professional Documents
Culture Documents
>> CalcArea
Menu
1. Rectangle
2. Circle
3. Sphere
Please choose one: 2
Enter the radius of the circle: 4.1
The area is 52.81.
>> CalcArea
Menu
1. Rectangle
2. Circle
3. Sphere
Please choose one: 1
Enter the length: 4
Enter the width: 6
The area is 24.00.
function []=ShowM
disp('Menu');
disp('1. Rectangle');
disp('2. Circle');
disp('3. Sphere');
end
ShowM();
if option==1
x=input('Enter the length:');
y=input('Enter the width:');
area=x*y;
elseif option==2
r1=input('Enter the radius of the circle:');
area=pi*(r1^2);
elseif option==3
r2=input('Enter the radius of the sphere:');
area=(4/3)*pi*(r2^3);
else
disp('error. please entire a valid option.');
end
3) Write a function CountPrimes(n1, n2) that will count the number of prime numbers between n1
and n2 and return the count as the output argument. Please implement this using a for loop.
Hint: you can use isprime(x) to check whether x is a prime number.
As an example,
num =
4
function CountPrimes(n1,n2)
count = 0;
for x = n1:n2
y = isprime(x);
if y
count = count + 1;
end
end
num=count
end
4) Write a function PrintCircles(n) that has one integer input argument n. This function prints out n
lines
of the capital letter ‘O’ with 1 to n ‘O’ in each line. Please implement this using a for loop. For
example,
>> PrintCircles(3)
O
OO
OOO
function PrintCircles(n)
for i=1:n
for j=1:i
fprintf('O');
fprintf('');
end
fprintf('\n');
end
You will earn extra 10 points if you print the circles in reverse order and right‐aligned as shown
below:
>> PrintCircles(3)
OOO
OO
O
x = [];
for i = 1:n
x = strcat('O', x);
s = [blanks(n-i) x];
disp(s)
end