You are on page 1of 2

Introduction to Taif University

Computer Programming Faculty of Engineering


803213-3 Electrical Engineering Dept.
Exercise Sheet #4 Fall 2017

1- Write a script file called ‘rect.m’ to calculate the area A of a rectangle


and its perimeter P given the length and width are already stored in
variables l and w respectively. Make sure the program displays the values
of A and P when calculated. Show how to use the script by an example.

Script file: rect.m


% assume l contains the value of the length
% and w contains the value of the width
A=l*w
P = 2 * (l+w)

To use the script:


l=10;
w=7;
rect;

2- Write down a script that asks the user to input three numbers a , b , and c
then calculates the sum s, the product p and the average m of the 3
numbers and finally displays the output “The sum is ” followed by the
value of s, and similarly for p and m.
Script file: sum_avg.m
a = input('First number : ');
b = input('Second number : ');
c = input('Third number : ');
s = a+b+c;
p = a*b*c;
m=s/3;
display(['The sum is ' mat2str(s)])
display(['The product is ' mat2str(p)])
display(['The average is ' mat2str(m)])

1
3- Write down a script to ask the user to input the radius r of a closed
cylinder and its heighth, then calculates and displays the cylinder base
area B=π r 2, its volume V =π r 2 h and its surface area A=2 πrh+2 π r 2.

File: cylinder.m
r = input('Cylinder radius = ?');
h = input('Cylinder height = ?');
B = pi * r^2
V = B*h
A = 2*pi*r*(h+r)

4- Write down a script to ask the user to input the coefficient of a quadratic
equation in the general form a x 2+ bx+ c=0 and print out the roots
−b ± √ b2−4 ac
x=
2a

File: quadratic.m
a = input('coefficient of x^2 : ');
b = input('coefficient of x : ');
c = input('free term : ');
d = sqrt(b^2 - 4*a*c);
x1 = (-b-d)/2/a;
x2 = (-b+d)/2/a;
display(['The roots are ' mat2str(x1) ' and ' mat2str(x2) ])

5- Write a script to print out the results of the following calculations: The
sun radiates 385 1024J/𝑠 of energy. Given the famous equation from Albert
Einstein: E=mc 2, calculate how much of the mass on the sun is used to
create this energy per day. If the mass of the sun is 2 ×1030kg, how many
years will it take to convert all the mass of the sun completely?

File: sunend.m
E=input('Energy per second');
c=3e8;
m=E/c^2;
MPD = m*3600*24;
disp(['Mass per day=' mat2str(MPD, 6) ' kg/day']);
MPY = 365.25*MPD;
M = input('Total mass');
years = M/MPY;
disp(['Years left ' mat2str(years,6) ' years']);

You might also like