while 루프 대신 for 루프를 사용하는 이유는 무엇입니까?
중복 가능성 :
for 루프 또는 while 루프로 반복 하시겠습니까?
C의 루프-for () 또는 while ()-어느 것이 가장 좋습니까?
언제 for루프 대신 루프를 사용해야 while합니까?
다음 루프는 구문을 제외하고는 동일하다고 생각합니다. 그렇다면 왜 다른 하나를 선택합니까?
int i;
for (i = 0; i < arr.length; i++) {
// do work
}
int i = 0;
while (i < arr.length) {
// do work
i++;
}
귀하의 경우 for루프 에서 코드 한 줄을 줄이는 것 외에는 많은 것을 얻지 못합니다 .
그러나 다음과 같이 루프를 선언하면 :
for(int i = 0; i < x; i++)
i나머지 코드로 이스케이프하는 대신 루프의 범위 내에서 유지하도록 관리합니다 .
또한 while 루프에는 변수 선언, 조건 및 증가가 3 개의 다른 위치에 있습니다. for 루프를 사용하면 편리하고 읽기 쉬운 한 곳에 모두 있습니다.
마지막 생각 :
하나 더 중요한 메모입니다. 둘 사이에는 의미 론적 차이가 있습니다. 일반적으로 While 루프는 무한 반복 횟수를 의미합니다. (즉, 파일을 읽을 때까지 .. 얼마나 많은 줄이 있는지에 관계없이) for 루프는 더 명확한 반복 횟수를 가져야합니다. (컬렉션의 모든 요소를 반복하며 컬렉션의 크기에 따라 셀 수 있습니다.)
선택 for하는 이유는 while가독성입니다.
for루프 를 사용하는 것은 초기화, "단계"작업 및 완료 조건이 필요한 일부 유형의 작업을 수행하는 것임을 명시 적으로 말하는 것입니다.
로 while, 다른 한편으로는, 당신은 말을하는지 당신은 완료 조건이 필요합니다.
카운터가 꼭 필요하지 않을 때 'while'을 사용합니다. 예를 들어 파일을 읽고 EOF에 도달하기를 기다리고있는 경우입니다. 이 경우 'for'가 최선의 대안이 아닐 수 있습니다. 배열의 항목을 살펴볼 때 의도를 더 잘 전달하기 때문에 'for'를 사용합니다.
for () 루프와 while () 루프의 한 가지 주목할만한 차이점은 while () 루프의 "continue"문은 루프의 맨 위로 분기되고 for () 루프의 하나는 세 번째 부분으로 분기된다는 것입니다. for () 절의 [조건 다음의 것, 일반적으로 변수를 범프하는 데 사용됨].
저는 교사로서 다양한 형태와 형태로 이것을 숙고 해 왔습니다. 내 제안은 항상
for-루프는 계산을위한 것입니다. 카운트 업, 카운트 다운.while/do-while구조는 다른 모든 조건을위한 것입니다.c!=EOF,diff<0.02등. 반복자 / 열거 형은 for 루프에 매우 적합한 카운터입니다.
즉 당신 int=0; while( ... )은 내 눈에 끔찍합니다.
펩시 대신 콜라를 선택하는 이유는 무엇입니까?
WHILE과 FOR 루프 사이에서 서로 바꿔서 사용할 수 있습니다. 순수 주의자가 되려면 조건의 특성에 따라 결정 기반을 만들 수 있습니다. 카운트 기반 루프를 수행하는 경우 FOR 루프가 가장 적합합니다.
for( cur = 0; cur < myList.Length; cur++ ){
doSomething( myList[cur] );
}
논리 기반 루프를 수행하는 경우 WHILE이 가장 깨끗한 구현을 만듭니다.
Iterator i = myObject.getIterator();
while( i.hasNext() ){
doSomething( i.next() );
}
당신이 말했듯이 그 이유는 성능보다는 의미적이고 심미적입니다 (그들의 컴파일 된 코드는 매우 유사한 경향이 있습니다).
즉, for알려진 반복 횟수가있는주기에서 일반적이지만 while, 조건이주기 내에서 수행중인 작업과 반드시 상관 관계가 없거나 처음에 반복 횟수를 알 수 없음을 의미합니다. 있다.
일반적으로 루프가 단일 위치에있는 유지 관리를 지역화하기 때문에 루프가 계수와 관련이없는 경우에도 항상 for 루프를 선호합니다. 누군가가 와서 루프를 추가 / 수정하기로 결정할 때 FOR 루프를 사용하는 경우 수정을 수행하는 사람은 일반적으로 FOR 표현식 내부의 항목을 엉망으로 만들지 않는 한 확신 할 수 있습니다. , 그들은 루프에서 반복을 중단하지 않을 것입니다.
그러나 while 루프와 같은 것은 프로그래머가 루프 본문을 완전히 구문 분석하고 반복되는 방법을 이해하여 루프 유지 관리 코드를 수정하지 않고 올바른 순서로 유지해야합니다.
따라서 FOR의 중간 부분 만 효과적으로 필요한 경우 에만 WHILE을 사용합니다.
기능적으로는 동일하지만 모든 루프 기능이 함께 있기 때문에 for 루프가 오류 발생 가능성이 적다고 주장 할 수 있습니다. i 선언, while 선언 및 인덱스 반복자를 구분하는 여러 줄이있는 경우 사용 방법에 따라 잊거나 혼동 될 수 있습니다. 물론 이것은 모두 주관적입니다.
프로그래밍 초기에 널리 퍼진 데이터 구조는 선형 배열 (일명 벡터)이었고 반복 패턴은 배열의 각 요소를 가로 질러 사용하는 것이 었습니다. 일반적으로이 시나리오는 언어에이 패턴에 대한 특정 구문 인 for 루프가 포함되어있었습니다. 이 역사적인 유산 외에도 while 루프를 모두 사용할 수 있습니다 (요즘에는 F #과 같은 기능적 언어에서는 List.map 또는 List.fold를 사용하고 싶습니다 ;-).
대부분 가독성의 문제입니다. 일반적으로 반복 할 값 범위를 정의한 경우 for 루프를 사용합니다. 반복하지 않거나 종료 조건이 언제 참인지 모를 때 while 루프를 사용하십시오.
자바 관점에서 for 루프는 컬렉션에 매우 편리합니다.
for (Object o : objects){
o.process();
}
다음보다 읽기가 훨씬 쉽습니다.
int i=0;
while(i < objects.size()){
objects.get(i).process();
i++;
}
일반적으로 동일한 최종 결과로 컴파일됩니다. 나는 대부분의 경우 for 또는 for-each를 선호합니다. 쓰기
for (;x<5;x++){
//do work
}
그렇게 불길하지는 않지만 쓰기
while(x<5){
x++
//do work
}
대신에
while(x<5){
//do work
x++
}
일부 사람들을 혼동하고 일대일 오류를 일으킬 수 있습니다.
Pascal과 같은 언어에서 for 및 while 구문은 다른 응용 프로그램을 가졌습니다. 다음과 같이 Pascal에서 for 루프를 작성합니다.
for i := 1 to 5 do
begin
{ some code here }
end
따라서 i가 1 씩 증가한다고 명시 적으로 명시합니다. 여기에는 명시 적으로 지정된 종료 조건이 없습니다. 따라서 실제 루프 실행이 시작되기 전에 미리 결정된 특정 횟수 동안 루프가 실행된다는 것을 알고있는 위치에서만 for 루프를 사용할 수 있습니다. 반면에 while 루프의 경우 명시적인 종료 조건을 지정할 수 있습니다.
i:=0;
while (i<>5) do
begin
{ some code here }
i:=i+1;
end
따라서 while 루프는 훨씬 더 유연합니다. 나중에 C가 개발되었을 때 for 및 while이 지원되었지만 for 구문의 의미가 변경되었으며 부울 연산자를 사용하여 명시적인 종료 조건을 추가 할 수 있습니다. 따라서 C 및 C와 유사한 언어에서 while 및 for의 힘은 동일하므로 사용성 문제보다 가독성 문제가 더 많습니다.
다른 (매우 좋은) 답변을 훑어 보면, 내가 확인되지 않은 점이 있습니다. (만든다면 놓치고 사과한다.)
나는 당신에게 의미 상 동일한 코드의 두 조각을 줄 것입니다.
스 니펫 # 1 :
for (int a = 0; a < arr.length; a++) {
/* do some work here */
}
스 니펫 # 2 :
int b = 0;
while (b < arr.length) {
// do work
b++;
}
똑같은 일을하는 것 같죠? 이제 각 스 니펫에 한 줄을 추가하고 어떤 일이 발생하는지 살펴 보겠습니다.
스 니펫 # 3 :
for (int c = 0; c < arr.length; c++) {
/* do some work here */
}
printf("%d\n", c);
스 니펫 # 4 :
int d = 0;
while (d < arr.length) {
// do work
d++;
}
printf("%d\n", d);
따라서 4 개의 스 니펫이 포함 된 정크 파일을 컴파일 할 때 (arr.length가 의미하는 일부 접착제 포함) 다음 오류가 발생합니다.
$ clang junk.c
junk.c:20:17: error: use of undeclared identifier 'c'
printf("%d\n", c);
^
1 diagnostic generated.
for루프를 사용하면 더미 카운터 변수 등에 더 많은 지역성을 제공 할 수 있습니다. 이렇게하면 충돌 가능성없이 변수 이름을 재사용 할 수있는 여유가 더 커집니다 (잠재적 인 섀도 잉이 증가하더라도).
일반적으로 while 루프와 for 루프의 차이점은 구문이며 성능과 관련이 없습니다. 즉,이 질문은 Java for loop 대 while loop에 대해 이미 해결 된 것 같습니다 . 성능 차이?
가독성. 그리고 옛 VB에서 6 일간의 wend를 볼 때마다 울고 싶었습니다.
while 루프를 사용하는 것이 좋은 경우가 있습니다. true / false를 반환하지만 해당 개체 내부의 값을 반복하는 개체에서 함수를 호출합니다.
C #에서 DataReader가되는 예 :
List<string> strings = new List<string>();
while(DataReader.Read())
{
strings.Add(DataReader["foo"].ToString());
}
for 루프를 사용하면 함수 내에서 작업을 캡슐화하여 더 나은 메모리 관리를 제공 할 수 있습니다. 또한 while 루프에 오류가있는 경우 모든 생명을 위협하는 제어 불능 루프가 될 수 있습니다.
bool keepGoing = true;
while(keepgoing)
{
try
{
//something here that causes exception, fails to set keepGoing = false;
keepGoing = false;
}
catch(Exception)
{
//Do something, but forget to set keepGoing.
//maybe there is always an exception...
}
}
나는 또한 그것이 일반적인 관행이라고 생각합니다. 건설과 매우 비슷합니다. 스터드에 루핑 플랫을 놓을 때 못을 사용합니다. 당신은 나사를 "사용할 수 있습니다", 그들은 같은 일을 할 것입니다. 그러나 그것은 단지 일반적인 관행이 아닙니다.
아무도 그것이 틀렸다고 말하는 것은 아닙니다. 우리는 단지 "코딩 세계가 계속 작동하도록 동료들의 압력을 받아 접어주세요"라고 말하는 것입니다.
There is a semantic difference between for and while loops. With for loops, the number of iterations is pre-defined, whereas with while loops it is not necessary.
Some languages (such as Ada) enforce this, by making the for loop counter a constant within the loop body. Hence it would be illegal to say, for example:
for i in values'range loop
...
i := i + 1; -- this is illegal, as i is a constant within the loop body
end if;
This semantic difference, however, is not so clear with most languages, which do not treat the for loop counter as a constant.
Just decide on one and then copy and paste / adjust it throughout your projects. Less decisions, less typing, faster coding. Negligible performance difference.
Also I am not with Justin keeping i in the scope of the loop, AND I use var aL = array.length outside the loop too. Then use i and aL within the for loop constructor so you are not recalculating the length of the array on each hit (along with a var creation over and over ;)). Again neg. performance really (see first bit of my answer), unless you have very big arrays flying around. If you happen to know the array length upfront initiate it with its fixed length first (slight help with memory allocation on crappy browsers ;) if this is client side and you have a lot of data).
js example
<script>
var i=0;
var myArray = ["D","R","Y"];//literal style will do for now;)
var aL=myArray.length; //or use 3 if known upfront
for(i;i<aL;i++){/*always do DRY things here*/}
</script>
also ensure when a condition is met, ask yourself "do I still need to complete the whole loop?" If not don't forget to break out of the loop as early as you can.
Related trivia:
In Google's new Go language, they have decided not to include the while statement. Instead they allow you to write a for statement that only has the condition clause. So the equivalent of
while (a < b) { ... }
is simply
for a < b { ... }
Simply put:
A 'for' loop tends to be used for iterational use. You need to iterate through an array, you need the numbers 1 through 100 (or other ranges) for various reasons.
A 'while' loop tends to be a conditional loop. You want to keep doing something until a contition is false. Assuming you have a class called 'Toast' and you wanted to cook the toast until it is toasted, you would have something like the following:
while (!toast.isToasted) cook(toast);
You can most always (I can't think of an example where you can't) write a for loop as a while loop and a while loop as a for loop, but picking the one which best first the situation usually comes down to my above points.
Readability is a very important point, but it works both ways. I'll convert a for-loop to a while-loop—even when I'm using a counter variable or it would otherwise be "natural" to use for—when it's more readable that way. This is common when you have a long or complex expression in any of for's three parts or multiple counters (which is related to being complex).
Knuth's loop-and-a-half also works better, in several languages, as an infinite loop with a break, rather than a for-loop.
However, there is a very important semantic difference:
for (int i = 0; i < arr.length; i++) {
if (filter(arr[i])) continue;
use(arr[i]);
}
int i = 0;
while (i < arr.length) {
if (filter(arr[i])) continue;
use(arr[i]);
i++;
}
Use for-loop when it's appropriate. The while solution has syntactic drawbacks (it's longer) and you have to check that you increment i before any continue call within the loop.
Preference. For me all the looping logic is built into the for statement so you do not have to declare the counter variable or do the increment/decrement stuff in the actual loop. Also, the you can declare the counter/index local to the for statement.
For loops are often easier to parallelize. Since the program can tell in advance the number of iterations that will be performed and the value of the iterator at any point, parallelization using an API such as OpenMP is trivial. Of course if you get into breaks, continues, and changing the iterator manually this advantage disappears.
because latter can be one liner: while (++i < arr.length) { // do work }
One reason is that a while's condition can be a string.
Also, if we add 'Do' to the mix, we can use a do while loop when we want the operation to run at least once regardless of its current state.
Its just my logic that we generally use for loop when we know the exact count of our itterations and we use a while loop when we generally want to check a condition.Then we use them according to ur requirments. Otherwise they both show same behaviour.
A while loop, defined as
while(condition)
represents this programming pattern:
1:
if(!condition) goto 2;
...
goto 1;
2:
Whereas a for loop, defined as
for(var i = seed; condition; operation)
represents this pattern:
var i = seed
1:
if(!condition) goto 2;
...
operation;
goto 1;
2:
Both patterns are so commonly used that they have been named and built into languages.
If you need to define a counter to control your loop, use a for loop. If not, use a while loop.
참고URL : https://stackoverflow.com/questions/3875114/why-use-a-for-loop-instead-of-a-while-loop
'program story' 카테고리의 다른 글
| jQueryUI 모달 대화 상자에 닫기 버튼 (x)이 표시되지 않음 (0) | 2020.11.09 |
|---|---|
| PHP에서 다차원 배열 전치 (0) | 2020.11.09 |
| 레이아웃 내의 모든보기를 비활성화하려면 어떻게해야합니까? (0) | 2020.11.09 |
| Scala REPL에서 타사 라이브러리를 사용하는 방법은 무엇입니까? (0) | 2020.11.08 |
| 채널의 모든 메시지 (~ 8K)를 Slack 정리 (0) | 2020.11.08 |