What Happens When X Equals To Zero or X Is Not Zero?

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

NAME _______________________________________ Date posted ____________

Terminal Number
EXERCISE 6A :
Do the following problems. Save you answer in word document and attached to EXERCISE 6A in
Blackboard.

1. Type the below for- loop command into MATLAB. How many times will the starred
line of the previous example be executed? What are starting point, increment (step)
and ending point of this loop?
Start:
Step:
End:
Total number of loops:

Calculate the sum S of elements ai =√2i-1, i=1, 2, ..., until the sum will exceed 20. Type
in the following code and examine the output.
S=0; % Initial assignment for sum to be able to check condition
i=1; % first value for i is 1
while S<20 %condition to check
S=S+sqrt(2*i-1); % recurrent formula for S
i=i+1; % next i
end
number_of_loops=i-1 % do you know why i-1?
S % shows the final value

2. What is wrong with the following code? Type it in MATLAB to check the error
message.
% This code assigns the value of x to zeroValue only % if x
is zero
x=4
if x=0
zeroValue = x
end
> What happens when x equals to zero or x is not zero?

3. Verify that the code below is correct by checking with a positive, negative and zero
value of x. It will be faster to run the code from a script M-file.
> Why don’t we need to check if x is actually zero when assigning it to zeroValue?

% If x is negative, assign value of x to negativeValue


% If x is positive, assign value of x to positiveValue
% If x is zero, assign value of x to zeroValue

x=4
if x<0
negativeValue = x
elseif x>0
positiveValue = x
else
zeroValue = x
end

4. Use a for- loop to print out the square of integers from


1 up to %maxValue.
maxValue = 10;
for num = % ** increment num from 1 to maxValue **
    num % this line simply prints num
    square = num^2 % this line prints the square
end

5. % Use a while- loop to print out the square of integers


from 1 up to maxValue.
maxValue = 10;
num=1;
while % ** num is not bigger than maxValue **
    num % this line simply prints num
    square = num^2 % this line prints the square
    num=num+1;
end

6. % Sam gets paid compound interest at a rate defined at 5%


per annum.
% Calculate his resulting investment each year and after 10
years.
% Change the rate on the 8th year to 5.75%
 
rate = 0.05;
investment = 5000;
for year = % ** increment the year from 1 to 10 **
    if % ** year is 8 **
       rate = 0.0575
    end
    year % this line simply prints the year
    investment = (1+rate)* investment % compounding function
end

You might also like