Tutorial eleven – looping in C

Storing data in an array is fine but we need code to access every element in an array. E.g. to work out the total of all the elements. For this we need to make our code run in a loop.

C has four ways to do loops but the last two are rarely if ever used. We’ll look at all four,

  • For-Loop
  • While-Loop
  • Do While-Loop
  • Goto -Label

For Loop

A for-loop looks like this with three loop sections before the body of the loop separated by semi-colons. The three loop sections are between the ().The body is the bit between { and }.

for (init variable; end condition; alter variable) {
Do something code.
}

Init variable sets the initial value of a loop variable. It can declare it as well.
End condition tests the value of the loop variable to see if the loop has finished
Alter variable changes the value of the loop variable.

The idea behind a for loop is that you are going to ruin the body of the for loop a specified number of times.

Here is a simple example that declares an array of ten ints and fills it with the squares of the numbers 0-9.

#include <stdio.h>

int squares[10];
int main() {
	for (int i = 0; i < 10; i++) {
		squares[i] = i * i;
	}
}

Lets look at the for loop. The three parts are

  1. int i = 0;
  2. i < 10;
  3. i++

1 Declares the loop variable i and sets it to 0. You must initialize the loop variable here.

2 Does a test. Is i < 10? The logic here is that the for loop continues as long as this test is true.

3. Increments i.

Although 2 and 3 occur before the body of the for loop, they are not done until after the for loop body has run. So the first value of i in the body of the for loop is 0 Squares[0] is assigned the value 0. Then i is incremented and the comparison i< 10 is evaluated.

At first glance this is a bit odd; Although the for loop is declared in this order init; compare; increment body, what actually happens is init body increment compare. It will become second nature to declare it this way.

While loop

Next most popular after a for loop is a while loop. This is easier as the syntax is a very easy

while (expression) {

    statement;

}

Where expression has to be true i.e. non-zero.  So you get code like this

int finished =0;
while (!finished) {
  finished = CheckCalculation();
}

Where CheckCalculation() is a function that returns a nonzero value when the calculation is complete.  Something to remember about while loops is that the while (expression) is calculated before the loop body so if if expression = 0 then the body is not run.

This contrasts with the less popular do-while loop which always runs omce.

Do-while loop

This is a while loop turned upside down.

The syntax is

do {

  statement;

} while (expression);

The while (expression) isn’t evaluated until after it has called statement once. This is a crucial difference between a while and a do-while.

Here is a simple example.

#include <stdio.h>

int main() {
	int finished = 0;
	int i = 1;
	do {
		printf("%d\n", i++);
		finished = i == 5;
	} while (!finished);

}

This counts from 1 to 4. After printing i with a value of 4, it is incremented and drops through the while (!finished).

The Goto statement

While strictly not a loop statement, you can use Gotos to create a loop. However just because you can doesn’t mean you should! There are few situations where a Goto can not be replaced by a for, while or do while loop.

Syntax.

Declare a label. This is a name with a :

goto label.

Here’s an example. It’s pretty bad code but it works and prints out the number 1-24 each on its own line.

#include <stdio.h>

int main() {
	int i = 1;
restart:
	printf("%d\n", i++);
	if (i < 25) goto restart;
}

The word restart is the label and the goto keep jumping to restart until i == 25. This is not a good piece of code and a for loop would be better used.

Finally lets look at the continue and break statements. These two statements are used mainly with loops and break is also used with a switch statement.

Continue and break

You can only use these inside a for, while or do while loop (and break in a switch). If you use continue then the loop immediately jumps to the next iteration. If you break, it immediately drops out of the loop.

Here’s an example of continue inside a for-loop.

#include <stdio.h>

int main() {
	for (int i = 0; i < 25; i++) {
		if (i % 2 == 0 || i % 5 == 0) continue;
		printf("%d\n", i);
	}
}

Can you guess what it does? It outputs all numbers 0-24 but if any number is even (0,2,4 etc) or a multiple of 5 (5, 10,15) it carries on with the loop. So it only oputputs 1,3,7,9, 11, 13,17,19,21 and 23 (each on a separate line).

Yes I could have reversed the if statement and called printf instead but sometimes doing a continue can simplify the logic.

#include <stdio.h>

int main() {
	for (int i = 0; i < 25; i++) {
		for (int j = 0; j < 25; j++) {
			if (j > i) break;
			printf("i=%d j=%d\n", i, j);
		}
	}
}

This is a somewhat confusing example. It’s a double loop and prints out the values of i and j but if j is ever bigger than i it does a break. The break means it drops out of thr for j loop and carries on inside the for i loop. So it only prints out values of i and j where j is less than or equal to the value of i. It’s a bit contrived, because I could have just put the condition in, if (i<= j) printf(…. to do the same. But is is more efficient.

With the break it does the j loop 1,2,3,4 according to the value of i (so roughly 1/2 of 625 loops) and without it (and using the if statement) it would do 625 loops and comparisons with if.

To see all tutorials

Link to previous tutorial.

Link to Next Tutorial (TBD)

(Visited 88 times, 1 visits today)