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. Anexample 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 0Number 1Number 2Number 3Number 4Number 5Number 6Number 7Number 8Number 9Number 10Number 11Number 12Press 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: JamesNew Student: JamesDo you have another students(y/n)? yEnter Student Name: PaulNew Student: PaulDo you have another students(y/n)? yEnter Student Name: BertrandNew Student: BertrandDo you have another students(y/n)? n

Copyright © 2002-2005 FunctionX, Inc.