User Tools

Site Tools


notes:cprog:spring2024: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:spring2024:projects:cnv0 [2024/03/05 00:38] – [for() loops] cgrant9notes:cprog:spring2024:projects:cnv0 [2024/03/06 20:54] (current) – [do-while loops] amelvil2
Line 33: Line 33:
     whatever you want to happen;     whatever you want to happen;
 } </code> } </code>
-====while() loops==== 
  
 +An example of a for loop that shows what iteration the loop is on, i.e Iteration: 0, Iteration: 1, etc. until it reaches Iteration: 9 and ends the loop:
 +<code>int i;
 +for (i = 0; i < 10; i++) {
 +    printf("Iteration: %d\n", i);
 +}</code>
 +====while() loops====
 +A while loop is a loop that continues to iterate as long as the input evaluates to true.
 +a while loop that iterates until an input variable reaches some designated value may look like:
 +<code>while (var != 100) {
 +    whatever you want it to do;
 +    }</code>
 +If you arent careful with your condition a while loop will iterate endlessly, preventing your code from moving past the loop
 +<code>unsigned int var = 0;
 +var = 20;
 +while (var == 20){
 +    do something that doesnt effect var;
 +    }
 +the rest of your code;</code>
 +In this case, because var never changes from 20, the while loop will never end
 +You can also achieve this endless iteration by typing
 +<code> while (true) {
 +    some code;
 +    }</code>
 +Because the condition is always true it will never escape the loop
 ====do-while loops==== ====do-while loops====
  
 +A do-while loop issues commands then checks the condition rather than checking the condition and then issuing the commands. 
 +
 +<code>
 +int i = 5;
 +do
 +{
 +    i--;
 +} while ( i > 0 )
 +</code>
 +
 +An example of a do-while loop being used. This loop will check if the user has inputted the correct password. The loop will continue until number equals 1234:
 +
 +<code>
 +int number;
 +do {
 +    printf("Enter the password: ");
 +    scanf("%d", &number);
 +} while (number != 1234);
 +</code>
notes/cprog/spring2024/projects/cnv0.1709599137.txt.gz · Last modified: 2024/03/05 00:38 by cgrant9