User Tools

Site Tools


notes:cprog:fall2024:projects:cnv0

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
notes:cprog:fall2024:projects:cnv0 [2024/09/29 03:40] – [for() loops] tkastne1notes:cprog:fall2024:projects:cnv0 [2024/10/01 16:40] (current) – [while() loops] tkastne1
Line 21: Line 21:
 <code> <code>
 for(int i = 10; i >= 0; i--){ for(int i = 10; i >= 0; i--){
-fprintf(stdout, "T minus %d\n", i);+    fprintf(stdout, "T minus %d\n", i);
 } }
 fprintf(stdout, "BLAST OFF!\n"); fprintf(stdout, "BLAST OFF!\n");
 </code> </code>
 ====while() loops==== ====while() loops====
 +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:
 +<code>
 +while(expression){code block}
 +</code>
 +
 +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
 +<code>
 +signed int value = 7;
 +while(value < 1000){
 +    fprintf(stdout, "value is %d\n", value);
 +    value = value * 2 + 3;
 +}
 +</code>
 +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
 ====do-while loops==== ====do-while loops====
 +do-while loops are used to repeat a block of code until a certain condition is no longer met
 +
 +The only difference between a do-while loop and a while() loop is that the block of code in a do-while loop is run unconditionally initially
 +
 +The format of a do-while loop is as follows:
 +<code>
 +do{code block}
 +while(expression);
 +</code>
 +The expression within parentheses will run every loop **after** the code block and is evaluated as a boolean
 +
 +The code block will run only again if the expression within the parentheses evaluates to true
 +
 +<code>
 +signed int value = 0;
 +do{
 +    fprintf(stdout, "value is %d\n", value);
 +    value = value * 2 + 3;
 +}
 +while(value > 0 && value < 1000);
 +</code>
 +This code prints value if it is between 0 and 1000 exclusive. However, value is printed while it is 0 because it was before the while() condition
  
notes/cprog/fall2024/projects/cnv0.1727581235.txt.gz · Last modified: 2024/09/29 03:40 by tkastne1