Home > database >  while loop replicating a for loop
while loop replicating a for loop

Time:05-01

Hi im trying to do a disk scheduling algorithm (C-SCAN).I have a for loop with an if statement that works, however im trying to change it to a while loop or another option to remove the break statement.

  for(i=0;i<n;i  )
    {
        if(initial<RQ[i])
        {
            index=i;
            break;
        }
    }

while ( initial>RQ[i] ) 
{ 
    index =i;

    i  ;     
}

The above for loop is what im trying to replicate as seen in my while loop. however it is not working the same way. any help will be much appreciated

CodePudding user response:

A for loop of the form

for (initialization; condition; repetition) {
    // body code
}

is equivalent to:

initialization;
while (condition) {
    // body code
    repetition;
}

So your loop would be rewritten as:

i = 0;
while (i < n) {
    if (initial < RQ[i]) {
        index = i;
        break;
    }
    i  ;
}

CodePudding user response:

One possibility of removing the break statement would be to introduce an additional flag variable which gets set when the loop should be terminated.

#include <stdbool.h>

[...]

bool terminate = false;

for( i=0; i<n && !terminate ; i   )
{
    if(initial<RQ[i])
    {
        index=i;
        terminate = true;
    }
}

However, I personally consider it better to use a break statement.

  • Related