The For Loop
We write code like this :
int i;
i = startvalue
while (test_involving i) {
statements
change_the_value_of_i
}
that they have implemented another control structure. The structure is
called a for loop.
for (initialization; condition; increment) {
statements
}
It performs exactly as the above loop.
- The initialization statement is performed
- The condition is checked, if it is false, we exit the loop
- Otherwise we execute the statemtnts
- We execute the increment
- We go back to step two.
For example, to count from 1 to 10
int i;
i = 1;
while (i <= 10) {
cout << " I is " << i << endl;
i++;
}
or
for (i=1;i<=10;i++) {
cout << " I is " << i << endl;
}
- The while is more general purpose
- The increment doesn't need to be at the end of a loop only
- It has been in almost every language
- The for statement is special purpose
- Our authors tell us that it is intended mainly for
counter controlled loops
- This is not my experience.
- None of the fields must be filled in,
- for (i=0;;) {
- i = 0; while (1);
- for (;x<7;) {
- while (x<7){
How about this code
// assume menu returns a choice a-d
char ch;
ch = menu()
while(('a' <= ch ) && (ch <= 'd') ) {
ch = menu();
}
for(ch=menu(); ('a' <= ch ) && (ch <= 'd'); ch=menu()) ;