How a while loop repeats code until its condition becomes false, shown with a counter that counts up to 100, and how it differs from the repeat until block in Scratch. From the lesson "Loops" in C programming basics (CS50 Shorts). Source: CS50 Shorts, "Loops" by CS50, Harvard University Original: https://cs50.harvard.edu/x/2024/shorts/loops/ Licence: CC BY-NC-SA 4.0 (https://creativecommons.org/licenses/by-nc-sa/4.0/) Changes: Cut from 1:22 to 2:21, reformatted to vertical with a blurred background and re-encoded; captions, summary and thumbnail by Upgram. Not endorsed by CS50 or Harvard University. Shared under the same licence.
You’ll learn how a C while loop repeats code while a condition is true, using a counter that starts at 0 and increments until it reaches 100. This is useful when you want a loop to stop based on a changing value rather than run forever. The loop stops at 100 because 100 is not less than 100.
Now, while loops are not always infinite. We can also replace the Boolean expression with something a little more useful than just true. So here's another example. While, and then some Boolean expression, and then curly braces. That's pretty much analogous to repeat until from scratch, although in a second I'll explain the difference. So in C, if the Boolean expression inside of the while loop evaluates to true, the lines of code between the curly braces will execute repeatedly over and over and over until Boolean expression evaluates to false. So for example, you might have some sort of counter. So say at the beginning of this loop you say int x equals 0. While x is less than 100, do a couple things inside that curly braces. Then at the end of your loop you say x plus plus. You're incrementing x, so eventually x will get to 100 and you will stop because the condition x is less than 100 will no longer be true as soon as x is equal to 100 because 100 is not less than 100.
Շարունակելու համար ներբեռնեք հավելվածը
Հավանեք, մեկնաբանեք, հետևեք հեղինակներին և վերահսկեք Ձեր առաջընթացը Upgram հավելվածում։
Ներբեռնել Upgram-ը
Մեկնաբանություններ