I know a while loop can do anything a for loop can, but can a for loop do anything a while loop can?
Please provide an example.
The basic premise is of the question is that while
loop can be rewritten as a for
loop. Such as
init;
while (conditional) {
statement;
modify;
}
Being rewritten as;
for ( init; conditional; modify ) {
statements;
}
The question is predicated on the init
and modify
statements being moved into the for
loop, and the for
loop not merely being,
init;
for (; conditional; ) {
modify;
}
But, it's a trick question. That's untrue because of internal flow control which statements;
can include. From C Programming: A Modern Approach, 2nd Edition you can see an example on Page 119,
n = 0;
sum = 0;
while ( n < 10 ) {
scanf("%d", &i);
if ( i == 0 )
continue;
sum += i;
n++;
}
This can not be rewritten as a for
loop like,
sum = 0;
for (n = 0; n < 10; n++ ) {
scanf("%d", &i);
if ( i == 0 )
continue;
sum += i;
}
Why because "when i
is equal to 0
, the original loop doesn't increment n
but the new loop does.
And that essentially boils down to the catch,
Explicit flow control inside the while
loop permits execution that a for
loop (with internal init;
and modify;
statements) can not recreate.