for variations
Each of the three
for sections can be
missing, with the consequence that it simply won’t be executed. In a
loop like the following, for example:
char c;
int b, m;
for(b = 0, m = 0; m + b <= 4;)
{
cout << "Is the new student bachelor or master\'s? (b/m) ";
cin >> c;
if(c == 'b')
b++;
else if(c == 'm')
m++;
}
the increment part is missing, so it is substituted by the increment statements
increasing
b and
m
in the body when appropriate. Notice how such variables both contribute to
control the iteration. They are both checked in a sum in the condition section,
and both are initialized in comma separated statements in the initialization
section.
Example
#include <iostream>
using namespace std;
int main()
{
char c;
int b, m;
for(b = 0, m = 0; m + b <= 4;)
{
cout << "Is the new student bachelor or master\'s? (b/m) ";
cin >> c;
if(c == 'b')
b++;
else if(c == 'm')
m++;
}
cout << "The number of bachelor students is " << b << " the one of master\'s is " << m;
}
Output
Is new student bachelor or master's? (b/m) b
Is new student bachelor or master's? (b/m) b
Is new student bachelor or master's? (b/m) m
Is new student bachelor or master's? (b/m) b
Is new student bachelor or master's? (b/m) m
The number of bachelor students is 3 the one of master's is 2