필터 지우기
필터 지우기

How many times does a loop repeat and end value?

조회 수: 3 (최근 30일)
Pam
Pam 2014년 12월 3일
편집: per isakson 2014년 12월 13일
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!

답변 (1개)

Image Analyst
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
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.
Pam
Pam 2014년 12월 4일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by