Effacer les filtres
Effacer les filtres

How many times does a loop repeat and end value?

3 vues (au cours des 30 derniers jours)
Pam
Pam le 3 Déc 2014
Modifié(e) : per isakson le 13 Déc 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!

Réponses (1)

Image Analyst
Image Analyst le 3 Déc 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 commentaires
Image Analyst
Image Analyst le 4 Déc 2014
Modifié(e) : Image Analyst le 4 Déc 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 le 4 Déc 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by