-1

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

4
  • 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? Jul 10, 2017 at 0:49
  • 4
    Use a language without for loops then you won't need to wonder about this. Jul 10, 2017 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 Jul 10, 2017 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, 2017 at 8:30

2 Answers 2

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.