Introduction to Programming and C++

Contents Previous Topic Next Topic

The only major difference between C++ and C for for loops is that the variables being iterated over cannot be declared in the for( ... ) statement. Thus, the correct form of a C for loop is shown in Program 1.

Program 1. A for loop.

#include <stdio.h>

int main() {
	int i;

	for ( i = -10; i < 10; ++i ) {
		printf( "%+d\n", i );
	}

	printf( "\n" );

	return 0;
}

In the original C language, all variables within a function had to be declared at the start of the function. Modern C compilers no longer require this. In general, it is still a good idea declare variables as close as possible to the first time they are used.


Questions

1. Replace the three lines

	int i;

	for ( i = -10; i < 10; ++i ) {

in Program 1 with

	for ( int i = -10; i < 10; ++i ) {

and see what happens.


Contents Previous Topic Top Next Topic