1) Please convert the for‐loop in the following codes to a while loop. Both versions (for‐ loop and while‐loop) should produce the same result.
x=0;
y=randi(100,1,5);
for i = 1:5
x=x+y(i);
end
disp(x);
Explanation of the given code:
x=0;
y=randi(100,1,5); //here upper limit=100 ,lower limit =1 and it generate any 5 random numbers between 1 and 100
for i = 1:5 // we are taking range of i from 1 to 5
x=x+y(i); // in this line we are adding the five random numbers.
end
disp(x); // we displaying the result of sum of five random numbers
NOTE: in this code we used randi function so result is not same when we run the code multiple time the function give different random numbers.
Here the given code (for loop) is taking randomly 5 numbers from the given range i.e., (100,1) and printing the sum of those 5 numbers
Here
upper limit= 100
lower limit=1
no of random numbers to be added=5
randi() function is used to generate random numbers in given range
So every time we execute the code we get different result
given for loop code with output
while loop code:
x=0;
i=0;
y=randi(100,1,5);
while i<5
i=i+1;
x=x+y(i);
end
disp(x);
output for while loop code:
Get Answers For Free
Most questions answered within 1 hours.