C++ Keywords: for

The for statement is typically used to count a number of items. It is made of three sections. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The formula of the for statement is:

for(Start; End; Frequency) Statement;

The Start expression is a variable assigned the starting value. An example would be Count = 0;

The End expression is an expression that sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24.

The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count.

Here is an example that applies the formula of the for statement:

#include <iostream>

using namespace std;

//---------------------------------------------------------------------------



int main(int argc, char* argv[])

{

    for(signed Count = 0; Count <= 12; Count++)

        cout << "Number " << Count << endl;



    return 0;

}

The program would produce:

Number 0

Number 1

Number 2

Number 3

Number 4

Number 5

Number 6

Number 7

Number 8

Number 9

Number 10

Number 11

Number 12



Press any key to continue...

Although we mentioned that a for statement is made of three sections, C++ allows you to create a for loop without specifying either one, two, or none of the three sections. To do this, you must still use the semi-colon delimiters of the sections but you don't have to include anything in the section. Based on this, you can create an empty for loop that appears as

for(;;) Statement;

Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char StudentName[10];

	char Answer[10];



	for(;;)

	{

		cout << "Enter Student Name: ";

		cin >> StudentName;

		cout << "New Student: " << StudentName << endl;



		cout << "Do you have another students(y/n)? ";

		cin >> Answer;

			

		Answer[0] = toupper(Answer[0]);

		if( Answer[0] != 'Y' )

			break;

		

		cout << endl;

	}



	return 0;

}

Here is an example of running the program:

Enter Student Name: James

New Student: James

Do you have another students(y/n)? y



Enter Student Name: Paul

New Student: Paul

Do you have another students(y/n)? y



Enter Student Name: Bertrand

New Student: Bertrand

Do you have another students(y/n)? n
 

Copyright © 2002-2005 FunctionX, Inc.