Answer to Question #101061 in MatLAB for Ayatollah

Question #101061
Examine the following for loops and determine the value of ires at the end of each of the loops and also the number of times each loop executes. Show your solutions.

1. ires = 0;
for index = 1:10
ires = ires + 1;
end

2. ires = 0;
for index = 1:10
ires = ires + index;
end

3. ires = 0;
for index1 = 1:10
for index2 = index1:10
if index2 == 6
break;
end
ires = ires + 1;
end
end

4. ires = 0;
for index1 = 1:10
for index2 = index1:10
if index2 == 6
continue;
end
ires = ires + 1;
end
end
1
Expert's answer
2020-01-09T04:11:25-0500

1. The loop will be executed 10 times. On each iteration a variable ires will be augmented by 1 starting from 0. So, after all, the value of ires will be 10.

Answer. 10.


2. The loop will be executed 10 times. On each iteration a variable ires will be augmented by the value of index starting from 0. So, after all, the value of ires will be the sum of all digits from 1 to 10, namely, 55.

Answer. 55.


3. The outer loop will be executed 10 times. On each iteration the inner loop will be executed 6-index1 times, namely 5,4,3,2,1 and 0 times and then 10 times after index2 becomes grater then 6. On each inner iteration a variable ires will be augmented by 1. So, after all, the value of ires will be 5+4+3+2+1 + 10 = 25

Answer. 25.


4. The outer loop will be executed 10 times. On each iteration the inner loop would be executed 10-index1 times if there were no following code:

if index2 == 6

continue;

end

In this case the answer would be 55, as far as on each inner iteration a variable ires is augmented by 1. But the variable index2 becomes 6 six times, so we loose 6 iterations. Thus, the value of ires will be 55-6 = 49.

Answer. 49.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS