answersLogoWhite

0


Best Answer

The golden rule in iteration: everything done with a for loop can be done with a while loop, BUT not all while loops can be implemented with a for loop. for-loops are just a short-cut way for writing a while loop, while an initialization statement, control statement (when to stop), and a iteration statement (what to do with the controlling factor after each iteration). = Examples of for-loops = The most basic use for using for-loops is to do something a set number of times: for(int k = 0; k < 10; k++); // this loops runs for 10 times another less common use of the for-loop is traversing raw listNodes, since it does contain an initialization(finding the first node), control (as long as there is a next node), and a iteration statement (get my next node). i.e.: for(ListNode temp = startingNode; temp != null; temp = temp.getNext); // this traverses the entire ListNode list and stops when it has exhausted the list = How to implement for-loops using while loop = Basically for loops are just short hand for while loops, any for loop can be converted from: for([initialize]; [control statement]; [iteration]); to [initialize]; while([control statement]) { //Do something [iteration]; } These two does the exact same thing. = For When Only while Loop can be used = while-loops are used when the exiting condition has nothing to do with the number of loops or a controll variable, maybe you just want to keep prompting the user for an input until the given input is valid, like the following example which demands a positive number: int x = [grab input]; while(x < 0) { // Do code

x = [grab input];

} It is true that, when used as intended, a for loop cannot do everything a while loop can, however, in reality, for loops are just as versatile. For example, the above while loop can easily be rewritten to be a for loop as so:

for(int x = [grab input]; x < 0; x = [grab input]){

// Do Code

}

The above for loop behaves exactly like the while loop in the previous heading. A better example of a while loop that should not be a for loop might be:

while(true){

// Do some processing

// Check some condition. If condition is met, break out of loop.

// Do some more processing.

}

Here, the checking of the condition comes in the middle of the processing for the while loop, whereas the condition checked in a for loop is always done at the beginning of the loop. Also, the "iteration" statement is non-existant and is a factor of processing done somewhere else in the while loop. Finally, there was no initialization for this while loop. However, this while loop can still be written as a for loop:

for(;true;){

// Do some processing

// Check some condition. If condition is met, break out of loop.

// Do some more processing.

}

As you can see, a for loop is exactly like a while loop if you leave out the initialization and iteration sections (you still needs the semicolons, to signify those parts of the for loop are still there, they just do nothing). However, it is clear that when you do not need the extra portions of the for loop, why not just use a while loop?

The basic for loop was extended in Java 5 to make iterating over arrays and other collections more convenient. See this website for further explanation:

(http://www.leepoint.net/notes-java/flow/loops/foreach.html)

User Avatar

Wiki User

16y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

9y ago

You will typically use a while loop whenever you need an infinite loop rather than a counted loop, which is best implemented using a for loop.

A while loop is basically just an extension of the simple if statement:

if (condition) { statement; }

When the if condition evaluates true, the statement executes, otherwise it does not. However the statement will only execute once at most.

A while loop is exactly the same in terms of syntax:

while (condition) { statement; }

The same thing happens with a while statement except that when the statement executes, the condition is re-evaluated. Thus the statement may be executed more than one time, for as long as the condition evaluates true.

By contrast, a do-while loop places the condition AFTER the statement. Thus the statement always executes at least once:

do { statement; } while (condition);

In some languages you might have a do-until loop rather than a do-while loop. The only difference is that the logic is reversed. So long as the condition evaluates false, the statement will be repeated; until the condition evaluates true.

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

A for loop should be used when you want to iterate - that is loop a specific, finite number of times. Generally a for loop is used when you are counting, or performing an operation on each element within a data structure.

While loops are used when you want to loop until an arbitrary condition is met, but you do not know how long it will take until it happens.

Note: in C, it's easy to transform a while-loop into a for-loop:

from: while (expression) statement

to: for (;expression;) statement

This answer is:
User Avatar

User Avatar

Wiki User

8y ago

A while or do-while loop is useful when we simply want to test if a condition holds before or after each iteration of a loop:

while (x) {

// ...

}

do {

// ...

} while (x);

To emulate these loops using for loops we'd need to use the following:

for (; x; ) {

// ...

}

for (;;) {

// ...

if (!x) break;

}

Regardless of which forms we use, the code generated is exactly the same. However, when we have a choice, we should always choose the code that is easiest to read because code that is easy to read is also easy to maintain. In this case, the while and do-while loops specify the intent much more clearly than the for loops.

A for loop is better suited to counted loops:

for (int x=0; x<100; ++x) {

// ...

}

Note that a for loop also provides localisation of the loop control variable. Here, the variable x will automatically fall from scope when the loop ends but a while or do-whileloop would not allow this. Sometimes that can be the deciding factor. However, if localisation is not an issue then the deciding factor is usually whether or not an action is required at the end of every iteration. If not, then a while loop is usually the better option. But if we need the loop to execute at least once then a do-while is the better option.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

Any time you need to repeat something a certain amount of times as long as you either know how many times or can give the program a way of knowing.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: When should a for loop be used instead of a while loop?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

In semaphore technique instead of while loop why for loop is used over there also what is the reason behind that ref-given in silberschatz of operating system concepts sixth edition book?

You should ask Silberschatz himself about that.


Which pair of loops causes a statement or set of statements to repeat as long as a condition is true?

A while loop repeats until the condition becomes false, and may never execute: int a = 4; while (a &gt; 5) { //Do something } or int a = 4; while (a &gt; 0) { //Do something a--; }


Which loop is used in php?

while, do...while, for, foreach are used


When should use a while loop over a do loop?

Generally speaking a for loop looks like this:for(Initialization;condition;increment){Do Stuff}whereas a while loop looks like this:while(condition){Do Stuff}Before the while loop there should be some initialization and somewhere in the Do Stuff section there should be statements that change the condition. Those statements are analogous to the increment section of the for loop.


What are control structures used in javascript?

The control structures used in java script are if-statement, for-loop, for-in loop, while loop,do-while loop, switch-statement, with-statement. try-catch-finally statements.


What is while statement and how is it used?

You use a while statement to introduce a conditional loop. Unlike a for loop which is typically used for counted loops, a while loop is used whenever a statement must iterate while an expression evaluates true. The expression is evaluated at the start of each iteration.


What is used to end a do loop?

A while statement.


What kind of loop is used to perform the loop until a special value is entered?

while


What is the significance of test condition in a loop?

The test condition in a loop is what's used to determine when the loop should end.


What are the types of loops?

There are three forms of loop commonly used in C/C++, the for loop, the while loop and the do-while loop. The for loop is most commonly used whenever an action is going to be performed a set amount of times. For example, to sum every element in an array: for(i = 0; i &lt; arraySize; i++) { sum = sum + array[i]; } The while loop and do-while loop are commonly used to loop until a condition is met. The difference between the two is that the do-while loop goes through one iteration before checking its condition, while the while loop checks its condition before any execution of the loop. Example do-while loop: do { randomNumber = rand() % 10; }while(randomNumber != 6); Example while loop: cout &gt; number; while(number &lt; 0) { cout &gt; number; }


What is the difference between while and for loop in c programming?

when use for loop user can assign the value of the variable inside the loop, while checking the condition. but in while loop he has to assign it out side of the loop. like for loop: for(i=5, n=2; i&lt;=8; i++) { n=n+5; } while loop: int i=5, n=2; while(i&lt;=8) { n=n+5; i++; }


What is the difference between a for loop and a while loop in java?

ComparisonThe conditions for both the 'while' and 'for' loop are exactly the same, but in each flow structure the conditions are placed in different locations. A 'for' loop places the full condition within the 'for' loop whereas the 'while' loop places the counter variable outside of the loop.The 'for' loop is used when the length of the loop is known whereas the 'while' loop is usually used when the length of the loop is unknown.'for' loop exampleWithin the parentheses the complete condition is contained. The condition has 3 parts delimited by a colon ';'. The first part sets the counter 'int i' to 0, the second part tells the loop to stop when the counter is 5. The third part tells java to increment the counter by 1 value each time the loop iterates.for ( int i = 0; i < 5; i++)'while' loop exampleWith the 'while' loop the counter is initialized outside of the 'while' loop. Inside the parentheses of the loop the condition is set to stop looping when the counter reaches a value of 5. Inside of the 'while' loop block the counter is set to increment by 1 value each time the loop iterates.int i = 0;while ( i < 5 ) {i++}