How many times does a loop repeat and end value?
3 次查看(过去 30 天)
显示 更早的评论
I am trying to figure this question out: 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.
(a) ires = 0;
for index = -10:10
ires = ires + 1;
end
(b) ires = 0;
for index = 10:-2:4
if index == 6
continue;
end
ires = ires + index;
end
(c) ires = 0;
for index = 10:-2:4
if index == 6
break;
end
ires = ires + index;
end
(d) ires = 0;
for index1 = 10:-2:4
for index2 = 2:2:index1
if index2 == 6
break
end
ires = ires + index2;
end
end
These are my results: a) ires=21 b)ires=22 c) ires=18 d)ires=24
But i was hoping someone could look it over I am a bit unsure of the last two. Thank You!
0 个评论
回答(1 个)
Image Analyst
2014-12-3
Why are you checking if the index equals 6? It doesn't look right at all. I'd do variants of
loopCounter = 0;
for index1 = 10:-2:4
for index2 = 2:2:index1
loopCounter = loopCounter + 1;
end
end
fprintf('This loop iterated %d times.\n', loopCounter);
2 个评论
Image Analyst
2014-12-4
编辑:Image Analyst
2014-12-4
Of course I know that. That's why I said variants . Do you really require me to do all cases (1) through (d) for you? I thought you'd be able to understand and do cases (a)-(c) if I just did case (d) for you - it's not hard. If I'm wrong let me know and I'll do all the cases for you.
And if you really want the breaking after the index = 6, you can put that in if you want (maybe it's just a part of the puzzle), you just need to decide if the iteration where it breaks is to be counted or not. If it is to be counted, put the loopCounter line before it, if it's not to be counted, put the loop counter after the "if" block.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!