Skip to content
UoL CS Notes

Loops in C

COMP281 Lectures

while

This checks the statement before running the statements:

while (<expression>) {
	<statements>
}

Be aware of the limits of the data-types you are using if you are including counters in your while loops. limits.h has information regarding maximum values.

do while

This checks the statement after running the statements:

do {
	<statements>
} while (<expression>)

for

The action is performed after every iteration:

for (<initialisation>; <continuation>; <action>) {
	<statements>
}

You can remove values, such as pre-initialised variables, like so:

int num = 10;
for (; num < 20;) {
	<statements>
	num++;
}

You can also create multiple counters like so:

for (int i, int j; i < 10 || j < 20; i++, j++) {
	<statements>
}

Other Flow Control Commands

continue

The continue statement jumps to the next iteration of a loop when encountered.

break

This statement “breaks” out of a loop.

This is often used in switch case constructs.

goto

This jumps directly to a label in the code:

goto label;
label:
<statement>

This is rarely used as is makes the code hard to read.