Loops - sheerazwalid/COMP-I GitHub Wiki

Loops

  • while loop
  • do while loop
  • for loop
  • continue statements
  • break statements inside loops

The following program prints "Hello" vertically in the console window. It is an example of a range-based for loop.

#include <iostream>

using namespace std;

int main() {
    string s = "Hello";
    for (char c : s) {
        cout << c << endl;
    }
    return 0;
}

Here is a program with the same behavior as the previous one but written with a traditional for loop.

int main() {
    string s = "Hello";
    for (int i = 0; i < s.size(); ++i) {
        cout << s[i] << endl;
    }
    return 0;
}

Here is a program with the same behavior as the previous but written with a while loop.

int main() {
    string s = "Hello";
    int i = 0;
    while (i < s.size()) {
        cout << s[i] << endl;
        ++i;
    }
    return 0;
}

Here is a program with the same behavior as the previous but written with a do-while loop.

int main() {
    string s = "Hello";
    int i = 0;
    do {
        cout << s[i] << endl;
        ++i;
    } while (i < s.size());
    return 0;
}

A loop written as a while loop and always be rewritten using a for loop and vice versa.

Additional Reading

Statements and Flow Control

Optional Videos

⚠️ **GitHub.com Fallback** ⚠️