C Programming

ITERATION, FOR LOOPS
The basic format of the for statement is,


	for( start condition; continue condition; re-evaulation )
		program statement;




	/* sample program using a for statement */
	#include <stdio.h>

	main()   /* Program introduces the for statement, counts to ten */
	{
		int  count;

		for( count = 1; count <= 10; count = count + 1 )
			printf("%d ", count );

		printf("\n");
	}


	Sample Program Output
	1 2 3 4 5 6 7 8 9 10

The program declares an integer variable count. The first part of the for statement


	for( count = 1;

initialises the value of count to 1. The for loop continues whilst the condition


	count <= 10;

evaluates as TRUE. As the variable count has just been initialised to 1, this condition is TRUE and so the program statement


		printf("%d ", count );

is executed, which prints the value of count to the screen, followed by a space character.

Next, the remaining statement of the for is executed


	count = count + 1 );

which adds one to the current value of count. Control now passes back to the conditional test,


	count <= 10;

which evaluates as true, so the program statement


		printf("%d ", count );

is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of 11.

When this occurs, the conditional test


	count <= 10;

evaluates as FALSE, and the for loop terminates, and program control passes to the statement


	printf("\n");

which prints a newline, and then the program terminates, as there are no more statements left to execute.



	/* sample program using a for statement */
	#include <stdio.h>

	main()
	{
		int  n, t_number;

		t_number = 0;
		for( n = 1; n <= 200; n = n + 1 )
			t_number = t_number + n;

		printf("The 200th triangular_number is %d\n", t_number);
	}


	Sample Program Output
	The 200th triangular_number is 20100

The above program uses a for loop to calculate the sum of the numbers from 1 to 200 inclusive (said to be the triangular number).


The following diagram shows the order of processing each part of a for


An example of using a for loop to print out characters


	#include <stdio.h>

	main()
	{
		char letter;
		for( letter = 'A'; letter <= 'E'; letter = letter + 1 ) {
			printf("%c ", letter);
		}
	}



	Sample Program Output
	A B C D E


An example of using a for loop to count numbers, using two initialisations


	#include <stdio.h>

	main()
	{
		int total, loop;
		for( total = 0, loop = 1; loop <= 10; loop = loop + 1 ){
			total = total + loop;
		}
		printf("Total = %d\n", total );
	}


	Sample Program Output
	Total = 55

In the above example, the variable total is initialised to 0 as the first part of the for loop. The two statements,


	for( total = 0, loop = 1;

are part of the initialisation. This illustrates that more than one statement is allowed, as long as they are separated by commas.


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