Investigate 13.1.
In your program, you want to use a loop to continuously get input from the user, and you want to continue to take in user input until a certain integer is entered.
for
vs. while
Loops
for
- and while
-loops can accomplish the same tasks, both have certain benefits and drawbacks. Here, we compare the syntaxes of both loops and discuss situations and scenarios in which one loop is preferable over the other.
for
-loop syntax:
for (initialization; loop run condition; update) {
statements...;
}
true
then the actual loop statements are executed once. Afterwards, the update statement is executed and next, the loop run condition is checked again. If still true, the loop statements are executed again, etc.
for (i=10; i>5; i--) {
printf("i = %d\n", i);
}
i
is initialized with the value 10 right before the start of the loop. Next, the logic statement i>5
is evaluated, and since 10 is indeed greater than 5, the loop is entered. The printf()
statement prints i = 10
to the screen. Next, the update statement i--
is executed, decreasing the value of i
to 9. The loop condition is checked (9 is still greater than 5) and so i = 9
is printed to the screen. i
is next decreased to 8, loop condition checked, etc. This continues on until i = 6
is printed to the screen. When i
is next decreased to 5, the check of the loop condition evaluates to false since 5 is not greater than 5. The loop terminates with the loop counter having the value 5.
while
-loop syntax:
while (condition) {
statements...;
}
i=10;
while (i>5) {
printf("i = %d\n", i);
i--;
}
for
loop. Notice that you have to explicitly initialize i
on your own before the loop and program the update condition i--;
as part of the loop body.
for
-loop when you have a known number of iterations.while
-loop when you have an unspecified number of iterations.for
-loop. We are asking the user to enter a positive number, and in case they accidentally put in a negative number, have them repeat the input.
scanf()
statement twice: once to read the user input and then one more time in case they entered something negative by accident. This is not the most elegant code (though perfectly acceptable). So there is a third kind of loop that helps in such a case, the do-while
-loop:
do-while
loop is guaranteed to execute its loop body at least once since it doesn’t get around to checking the loop condition until after execution of the loop body.
while
-loops and do-while
-loops do you notice? Are there any similarities in their syntaxes?