are all while loops convertible to for loops?

Viewed 78

earlier, I thought that we can't use for loops when working with linked lists... but then for(current = head; current != NULL; current = current->next) this line made me think. is all while loops are convertible to for loops especially when there is more than one condition?

3 Answers

Yes anything which can be written in a while loop can be represented with a for loop. Both of them are entry controlled loops which means first they check the condition and then the body is executed.

For a loop to run properly, we need at least one thing, i.e. condition and at most 3 things:

  1. Initialization of the looping variable (If necessary)
  2. Condition (Necessary)
  3. Modification to the looping variable (If looping variable is initialized)

Now I will present a simple code block with both while and for loops:

-> To print all naturals numbers from 1 to 100.

Using While loop

int i=1; //Initialization of looping variable
while(i<=100) //Condition check
{
    cout<<i;
    i++; //Increment (Modification of looping variable)
}

Using For loop

Method 1:

for(int i=1;i<=100;i++)
//Here the first part to the for is initialization of looping variable.
// Second part is the Condition
// Third part is the increment
{
    cout<<i;
}

Method 2:

int i=1;//Initializing the loop variable
for(;i<=100;)//Condition
{
    cout<<i;
    i++;//Increment
}

I gave this 2 methods to write the For loop, to show that both while and for loop can run only with the condition. If we are capable enough to rewrite the code in the format we need, both will run exactly in the same way.

You can use for loops in this instance because you are iterating a specific number of times (once per item in the list). It's not super intuitive but most purely programming related you could manage to change from a purely true/false run condition to a bounded countable run condition.

This line of thinking breaks down very quickly if you involve any amount of hardware. Let's say you have a program that turns on an LED so long as you hold down a button.

while(button is down) { LED = ON; }

Something like this you wouldn't want to do with a for loop because there is no way of counting something to know when you stop, the amount of time is decided by the person holding down the button and can't be known by the computer until it actually happens.

TL;DR: You can use for loops for a lot of things that aren't intuitive. But you can't use them to replace EVERY possible while loop.

Some code example from my code, using while in a way that I wouldn't replace it with a for.

public function generateUniqueTokenForEntity(){
    while (true) {
        $token = substr(md5(uniqid()), 0, 10);
        $entry = $databaseTable->findEntryByToken($token);
        if ($entry === null) {
             return $token;
        }
    }
}
Related