C Programming

Graphical Animation of for loop
To demonstrate the operation of the for statement, lets consider a series of animations.

The code we will be using is


	#include <stdio.h>

	main() {
		int x, y, z;

		x = 2;
		y = 2;
		z = 3;

		for( x = 1; x <= 6; x = x + 1 ) {
			printf("%d", y );
			y = y + 1;
		}
		printf("\n%d", z );
	}
			

	Sample Program Output
	2 3 4 5 6 7
	3


The following diagram shows the initial state of the program, after the initialization of the variables x, y, and z.

for part1

On entry to the for statement, the first expression is executed, which in our example assigns the value 1 to x. This can be seen in the graphic shown below (Note: see the Variable Values: section)

for part1

The next part of the for is executed, which tests the value of the loop variable x against the constant 6.

for part1

It can be seen from the variable window that x has a current value of 1, so the test is successful, and program flow branches to execute the statements of the for body, which prints out the value of y, then adds 1 to y. You can see the program output and the state of the variables shown in the graphic below.

for part1

After executing the statements of the for body, execution returns to the last part of the for statement. Here, the value of x is incremented by 1. This is seen by the value of x changing to 2.

for part1

Next, the condition of the for variable is tested again. It continues because the value of it (2) is less than 6, so the body of the loop is executed again.

Execution continues till the value of x reaches 7. Lets now jump ahead in the animation to see this. Here, the condition test will fail, and the for statement finishes, passing control to the statement which follows.

for part1


Play "for" animation [AVI, 4.4MB, CD-ROM only]
Play "for" animation [Real Video, 740KB, CD-ROM only]


©Copyright B Brown. 1984-1999. All rights reserved.