-1

How do you determine when and where to use a for loop in programming?

closed as too broad by whatsisname, gnat, Bart van Ingen Schenau, David Arno, Basile Starynkevitch Jul 10 '17 at 10:30

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    Are you referring to loops in general, or are you referring to using a for loop instead of another kind of loop such as a while loop? – Greg Hewgill Jul 10 '17 at 0:49
  • 4
    Use a language without for loops then you won't need to wonder about this. – Derek Elkins Jul 10 '17 at 2:43
  • generally, whenever i am iterating over a list of objects, and there is no need for queue keeping, and no need to change the collection while iterating, i go with a foreach, otherwise, backwards for-loops, or even while loops – Timothy Groote Jul 10 '17 at 7:28
  • 4
    If you copy the same code more than 100 times, you should use a for loop. If you copy it 99 times, you might think about it. – gnasher729 Jul 10 '17 at 8:30
2

It is good to use the for loop when you know how many iterations you have to do, depending on a value.
At the opposite, you should use the while loop when your loop have to stop depending on a different type of parameter.
Let's see two example in C++ :

For loop

Here we have a very simple case of using the for loop

int StopValue = 10
for ( int i = 0; i<StopValue ; i++)
{
    cout<<i<<endl;
}

While loop

Here we have a simple chained List, which we would like to check how many link we have :

struct Node {
    int x;
    Node *nextNode;
}

// Declaration & initialization of your chained list

// Check how many link we have 
Node* head= YourFirstNode;
int NumOfLink =0; 
while (head->nextNode != nullptr)
{
    NumOfLink ++;
    head = head->nextNode;
}
1

Loops are used to perform the same operation to different data in sequence.

If loop exit condition is known in advance, you can use a for loop.

Not the answer you're looking for? Browse other questions tagged or ask your own question.