Site icon Study Algorithms

Different types of loops in C

There are 3 loops in C: for, while, do-while. Here is a bit detail about them:-

A while loop will always evaluate the condition first.

while (condition)
{
    //gets executed after condition is checked
}

A do/while loop will always execute the code in the do{} block first and then evaluate the condition.

do
{
    //gets executed at least once
} while (condition);

A for loop allows you to initiate a counter variable, a check condition, and a way to increment your counter all in one line.

for (int x = 0; x < 100; x++)
{
    //executed until x >= 100
}

At the end of the day, they are all still loops, but they offer some flexibility as to how they are executed.


For loops are especially nice because they are concise. In order for this for loop

for (int x = 0; x < 100; x++)
{
    //executed until x >= 100
}

to be written as a while loop, you’d have to do the following.

int count = 0;
while (count < 100)
{
    //do stuff
    count++;
}

In this case, there’s just more stuff to keep up with and the count++; could get lost in the logic. This could end up being troublesome depending on where count gets incremented, and whether or not it should get incremented before or after the loop’s logic. With a for loop, your counter variable is always incremented before the next iteration of the loop, which adds some uniformity to your code.

What about break and continue statements?

break will instantly terminate the current loop and no more iterations will be executed.

//will only run "do stuff" twice
for (int x = 0; x < 100; x++)
{
    if (x == 2)
    {
        break;
    }
    //do stuff
}

continue will terminate the current iteration and move on to the next one.

//will run "do stuff" until x >= 100 except for when x = 2
for (int x = 0; x < 100; x++)
{
    if (x == 2)
    {
        continue;
    }
    //do stuff
}
Exit mobile version