Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN MATLAB Write a program that prompts the user as to how many numbers he/she wa

ID: 669999 • Letter: I

Question

IN MATLAB

Write a program that prompts the user as to how many numbers he/she wants in the array and then accepts that many integers from the user. If the user enters a non-integer, the user is warned about it with a message, “Hey that is not an integer – I’m rounding it up to !”, stores those numbers in an array, and once all the numbers are entered, it displays it. From this array, create two arrays – one that contains all the even numbers of the original array and another that contains all the odd numbers. Display both.

Explanation / Answer


count = str2double(input('Please enter the array size as an integer only: ', 's' ) );
if isnan(count) || fix(count) ~= count   % is nan will check for it is Not A Number?
   disp('Hey that is not an integer – I’m rounding it up to !');
end
% loop from 1 to count
% receive array elements or items one by one from the user
% store those into array mainArray
for i from 1 to count do
   mesg = 'Enter the array element or item: ' ;
   item = input(mesg);
   mainArray(i) = item;
end_for
i := 1;
for i from 1 to count   do % print the full array received both odd and even
   print(mainArray(i))
end_for;
% the bitget(item,1) built in function will convert the number into binary and
%   get the least significant bit (LSB) for odd numbers it is 1 like 01,11,101,1101,1001 etc
%   (they are the binary equivalent of 1,3, 5 etc)
% if LSD is 0 then it is an even number
% collect all odd number into oddArray and even numbers into evenArray
j := 1;
k := 1;    

for i from 1 to count   do
   if bitget(mainArray(i), 1)
       oddArray(j) = item;
       j = j + 1;
   else
       evenArray(k) = item;
       k = k + 1;
   end
end_for;    % split the mainArray into evenArray and oddArray
for i from 1 to j do
   print(oddArray(i))
end_for;
for i from 1 to k do
   print(evenArray(i))
end_for;