Azzera filtri
Azzera filtri

How many times does a loop repeat and end value?

3 visualizzazioni (ultimi 30 giorni)
Pam
Pam il 3 Dic 2014
Modificato: per isakson il 13 Dic 2014
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!

Risposte (1)

Image Analyst
Image Analyst il 3 Dic 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 Commenti
Image Analyst
Image Analyst il 4 Dic 2014
Modificato: Image Analyst il 4 Dic 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.
Pam
Pam il 4 Dic 2014
Ok thank you I mean I do have my answers there so I understand the question I just wanted someone to see if they were okay. Thank you for more in depth information, I do appreciate it.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by