C++ Loops

🔁 C++ Loops – while, do-while, and for Explained Simply

Loops let you repeat code without writing it over and over. Want to count sheep until you fall asleep? Use a loop! 🐑💤

C++ gives you three main types of loops:

  • while loop – Repeats while a condition is true
  • do-while loop – Like while, but runs at least once
  • for loop – Great for counting a fixed number of times

🔄 while Loop

Repeats the block as long as the condition is true.

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    while (i <= 5) {
        cout << "Count: " << i << endl;
        i++;
    }
    return 0;
}

Try It Now

🔁 do-while Loop

Runs the block at least once, even if the condition is false.

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    do {
        cout << "Do Count: " << i << endl;
        i++;
    } while (i <= 5);
    return 0;
}

Try It Now

🔢 for Loop

Perfect when you know how many times to loop!

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << "For Count: " << i << endl;
    }
    return 0;
}

Try It Now

💡 Loop Tips

  • Use while when you’re unsure how many times to loop.
  • Use do-while when you want the code to run at least once.
  • Use for when you’re counting or know the number of repetitions.

Loops = Less writing, more doing! 🧠💪