In: Computer Science
Matlab
For a vector x=[1,10,-5,72,56,70,33] a) Use for loop to sum the vector x and count how many values are greater than 33. b) Repeat (a), this time a while loops.
code:
x=[1,10,-5,72,56,70,33]
sum = 0
count = 0
%doing with for loop
for i = 1:length(x)
%adding to variable sum
sum+=x(i)
%checking if number is grater than 33
if x(i)>33
%increment the count
count++
end
end
fprintf("Sum of values : %d",sum)
fprintf("\nTotal %d numbers are greater than 33",count)
code:
x=[1,10,-5,72,56,70,33]
sum = 0
count = 0
%doing with while loop
i=1
while i<=length(x)
sum+=x(i)
if x(i)>33
count++
end
%incrementing loop variable
i++
end
fprintf("Sum of values : %d",sum)
fprintf("\nTotal %d numbers are greater than 33",count)