You are on page 1of 3

1) Write a single function CalcArea( ) that has no input/output arguments.

The function will first print a


“menu” listing 3 items: “rectangle”, “circle”, and “sphere”. It prompts the user to choose an option, and
then asks the user to enter the required parameters for calculating the area (i.e., the width and length of
a rectangle, the radius of a circle or a sphere) and then prints its area. The script simply prints an error
message

for an incorrect option. Here are two examples of running it:

>> 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();

option= input('Please choose one (1,2,3):');

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

fprintf('The area is %.2f\n',area)


2) Write a script that uses a for loop to print a vector of numbers from 100 to 300 in a step of 50 in
exactly the following format:

Number 1 is: 100


Number 2 is: 150
Number 3 is: 200
Number 4 is: 250
Number 5 is: 300
j=0;
for i=100:50:300
for j=j+1
fprintf('Number %d is: %d\n',j,i)
end
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=CountPrimes(10, 20)

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,

calling the function should output something like this:

>> 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

You might also like