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

Problem (3): Write a program that (a) generates a vector with 20 random integer

ID: 3600904 • Letter: P

Question

Problem (3): Write a program that (a) generates a vector with 20 random integer elements with integers between 10 and 30., (b) replaces all the elements that are not even integers with random integers between 10 and 30, and (c) repeat (b) until all the elements are even integers. The program should also count how many times (b) is repeated before all the elements are even integers. When done, the program displays the vector and a statement that states how many iterations were needed for generating the vector.

Explanation / Answer

The script has been written as desired. The function "randi" has been used to generate random integers.

randi(a,b,c) generates a b x c matrix containing integers in the range [1:a].
randi(a) generates one integer in the range [1:a]

First, random numbers in the range [1:21] were generated. Then 9 was added to each number to bring them to the range [10:30] as asked in the question.


-------------- The script ---------------

arr = randi(21,1,20);
% This generates a 1x20 vector of numbers in the range 1 to 21
arr = arr + 9; % Numbers are now in the range 10 to 30

count = 0;

while(true)
flag = true; % flag stores true if all are even
for i=1:20
if mod(arr(i),2)==1
arr(i) = randi(21)+9; %Same logic as above
flag = false; % flag set to false because odd number found
end
end
if flag  % all numbers are even
break;
end
count = count+1;
end
fprintf('The vector is: ');
disp(arr);
fprintf('%d iterations were needed for generating the vector ',count);

--------------- Sample output -------------------

The vector is:
24 12 30 16 22 10 16 10 20 26 24 22 18 26 22 24 12 26 16 28

4 iterations were needed for generating the vector

Please rate my answer if you find this useful. Have a good day.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote