Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Conditional loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Types== The following types are written in [[C++]], but apply to multiple languages. ===While loop=== Checks condition for truthfulness before executing any of the code in the loop.<ref>{{Cite web |title=while loop - cppreference.com |url=https://en.cppreference.com/w/cpp/language/while |access-date=2023-11-07 |website=en.cppreference.com}}</ref> If condition is initially false, the code inside the loop will never be executed. In [[PL/I]] this is a <code>DO WHILE...</code> statement. <syntaxhighlight lang="c++"> while (condition) { // code } </syntaxhighlight> ===Do-While loop=== Checks condition for truthfulness after executing the code in the loop. Therefore, the code inside the loop will always be executed at least once. PL/I implements this as a <code>DO UNTIL...</code> statement. <syntaxhighlight lang="c++"> do { // code } while (condition); </syntaxhighlight> ===For loop=== A simplified way to create a while loop.<ref>{{Cite web |title=for loop - cppreference.com |url=https://en.cppreference.com/w/cpp/language/for |access-date=2023-11-07 |website=en.cppreference.com}}</ref> <syntaxhighlight lang="c++"> for (initialization; condition; statement) { // code } </syntaxhighlight> '''Initialization''' is executed just once before the loop. '''Condition''' evaluates the boolean expression of the loop. '''Statement''' is executed at the end of every loop. So for example, the following while loop: <syntaxhighlight lang="c++"> int i = 0; while (i < 10) { // code i += 1; } </syntaxhighlight> Could be written as the following for loop: <syntaxhighlight lang="c++"> for (int i = 0; i < 10; ++i) { // code } </syntaxhighlight> ===For-Each loop=== A for-each loop is essentially equivalent to an [[iterator]]. It allows a program to iterate through a data structure without having to keep track of an index. It is especially useful in Sets which do not have indices. An example is as follows: <syntaxhighlight lang="c++"> std::vector<std::string> range = { "apple", "banana", "orange" }; for (auto item: range) { // code } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)