How many times does a loop repeat and end value?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Image Analyst
am 3 Dez. 2014
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 Kommentare
Image Analyst
am 4 Dez. 2014
Bearbeitet: Image Analyst
am 4 Dez. 2014
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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!