Skip to content

Instantly share code, notes, and snippets.

@forksofpower
Last active February 8, 2017 04:25
Show Gist options
  • Save forksofpower/a827b674d720fa549d96ff038aefe7f8 to your computer and use it in GitHub Desktop.
Save forksofpower/a827b674d720fa549d96ff038aefe7f8 to your computer and use it in GitHub Desktop.
FOR vs WHILE vs DO-WHILE
// Iteration
// The FOR, WHILE and DO-WHILE structures are similar in that they both allow you to repeatedly
// run code in a loop until a condition is met.
// FOR loops iterate a give number of times, represented here by the variable 'i'
// the variable is set to 0 and the FOR loop is told to increment 'i' by one (i++)
// until the condition (i < 100) is met.
int age = 50;
for (int i = 0; i < 100; i++) {
age += 2;
}
std::cout << "The new age is " << age; // The new age is 250
// WHILE loops do not require the programmer to set the number of times it will iterate
// and will continue to run until the condition (name != "Homer Simpson") is met.
String name = "Some Name";
while (name != "Homer Simpson") {
name = getRandomName();
}
// DO-WHILE is the same as WHILE but runs the code contained within once first before checking the conditional
// This example creates a fake database connection and then runs the database.connect() method once to try to
// connect. If the connection status is not "connected" then keep retrying until it does.
Connection database = new Connection();
do {
database.connect();
} while (database.status != "connected");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment