C also has a convenience loop that combines the initialization, condition, and housekeeping into the beginning of the loop, but unlike Fortran's do loop, it is not less flexible than a while loop. The C for loop is a condensed while loop. It simply collects the initialization, condition, and housekeeping into one place for the sake of readability.
for (initialization; condition; housekeeping) body
/*************************************************************************** * Description: * Print sine of every angle in degrees from 0 to 360 ***************************************************************************/ #include <stdio.h> #include <math.h> #include <sysexits.h> int main(int argc,char *argv[]) { double angle; // Condition for ( angle = 0.0; angle <= 360.0; angle += 1.0 ) // Body printf("sine(%f) = %f\n", angle, sin(angle * M_PI / 180.0)); return EX_OK; }
What is one advantage and one limitation of C for loop compared with a while loop?
Rewrite the square roots program from the previous section using a C for loop.