Write programs with loops that compute:
(a) The sum of all even numbers between 2 and 100 (inclusive).
(b) The sum of all squares between 1 and 100 (inclusive).
(c) The sum of all odd numbers between a and b (inclusive), where a and b are inputs.
(d) Ask the user for a sequence of integer inputs and print: The smallest and largest of the inputs.

Respuesta :

Answer:

The programs are written in MATLAB.

(a)

sum = 0;

for i = 2:100  %This for loop starts from 2 and ends at 100

   sum = sum + i;  %This line sums each values of the loop

end

disp(sum); %This command displays the sum at command window

(b)

sum = 0;

for i = 2:100

   sum = sum + i^2;  %This line sums the squares of each values in the loop

end

disp(sum);

(c)

sum = 0;

a = input('Please enter a: ');

b = input('Please enter b: ');

for i = a:b

   if mod(i,2) == 1  %This command checks whether the value in the loop is odd or not

       sum = sum + i;  %This command sums each odd value in the loop

   end

end

(d)

seq = input('Please enter a few numbers with square brackets [] around them: ');

small = seq(1);  %Initialize small

large = seq(1);  % Initialize large

for i = 1:length(seq)  %Iterate over the sequence

   if seq(i) < small

       small = seq(i);  %Decide if the value in the loop is smallest

   elseif seq(i) > large

       large = seq(i);  %Decide if the value in the loop is largest

   end

end

fprintf('The smallest of the inputs is %g,\nThe largest of the inputs is %g.\n',small,large);