This is an old revision of the document!
for() loops are used to repeat a block of code a certain amount of times
for() loops have a fixed format
for(first; second; third){code block}
The first expression is executed once at the start of the statement. The second expression must evaluate to a boolean and is evaluated before every loop. The third expression is executed after every loop.
The following is an example of how a for() loop can be used
for(int i = 10; i >= 0; i--){ fprintf(stdout, "T minus %d\n", i); } fprintf(stdout, "BLAST OFF!\n");
while() loops are used to repeat a block of code until a certain condition is no longer met
The format for a while loop is as follows:
while(expression){code block}
The expression within parentheses will run every loop before the code block and is evaluated as a boolean
The code block will run only if the expression within the parentheses evaluates to true
signed int value = 7; while(value < 1000){ fprintf(stdout, "value is %d\n", value); value = value * 2 + 3;
The loop in this code runs 7 times, outputting 7, 17, 37, 77, 157, 317, and 637; stopping before printing 1277
while() loops are best used when the amount of times a block of code is intended to run is not explicit or simple to calculate