Skip to main content

Loops

[C++] Loops and its Types

Imagine you have an obedient robot which does your household chores: you want it to repeat the same action, like sweeping the floor, again and again without having to yell “sweep more!” every single time.

Loops in C++ let you automate repetitive tasks by telling the computer: “Hey, keep doing this until I say stop!”

If you’ve never coded before, don’t worry! We’ll take tiny steps and look at real code examples too. Ready to teach your computer some tricks? Let’s jump in together!

What Is a Loop in Programming?

A loop is a way to tell the computer, "Repeat this set of actions as long as a certain condition is true."

But why do you need them?

  • Computers are great at repeating stuff. Loops make that possible.
  • Without loops, you’d have to copy and paste the same instructions again and again. Yikes!

Think of a loop as a merry-go-round: as long as you keep saying “one more time,” the ride continues. As soon as you say “stop,” everyone gets off.

I’ll let you know what you’ll be learning and why it matters.

What’s Coming Up?

Here’s our roadmap:

  1. The big idea: What is a loop, anyway?
  2. How to use the while loop, step by step.
  3. How to use the for loop, step by step.
  4. How the do-while loop works, and why it’s a bit different.
  5. Infinite loops: what they are, when they’re helpful, and how to avoid them by accident.
  6. A gentle intro to “time complexity”, so you’ll know if your loop makes your code speedy or slow.

Now let's get deeper into the C++ "while" loop.

The “while” Loop: What It Is and How to Use It

The while loop is the simplest loop in C++. Here’s what it means: “As long as this statement is true, keep doing this.”

Structure of a while loop:

while (condition) {
    // Do something
}

Let’s break this down:

  • while — this is a keyword, a special programming word that starts the loop.
  • (condition) — This is a test, like “Is it raining?” If the answer is yes/true, the loop runs. If the answer is no/false, it stops. Here, we decide when the loop should stop running.
  • { ... } — the curly braces surround the block of code to be repeated.

Example: Counting from 1 to 5

Let’s say you want the computer to print numbers 1 through 5. Here’s what that looks like:

int i = 1; // Start with 1
while (i <= 5) {           // As long as i is less than or equal to 5
    cout << i << endl;  // Print the value of i
    i++;                   // Make i one bigger
}

Explanation, step by step:

  • int i = 1 — This line creates a starting point. Think of it like putting a chalk mark at “1” on the ground.
  • while (i <= 5) — Checks if i is still 1, 2, 3, 4, or 5. If so, keep going!
  • cout << i << endl — Print i out.
  • i++ — Make i bigger by 1 (go from 1 to 2, then 2 to 3, etc.).

The loop stops when i becomes 6, which doesn’t satisfy the condition anymore.

Key Things to Remember:

  • If the condition is never true to start with, the loop never runs.
  • If the condition never becomes false, you’ll get stuck in an endless loop, and your computer might freeze! We will look at it later in the article.

Now that we know what a while loop is. Let's shift our focus towards the C++ "for" loop.

The “for” Loop: Walkthrough and Examples

The for loop is a favourite for counting or when you already know how many times you want to do something.

Structure of a for loop:

for (initialisation; condition; updation) {
    // Do something
}

Let’s talk about each part:

  • initialisation — Set your starting point (e.g., int i = 0)
  • condition — Ask, “Should I keep going?” (i < 10)
  • updation — Say what happens after each turn (i++ or i+=1, means add one)

Imagine you're stacking books on a shelf:

  • Take the first book from the pile.
  • Place it on the shelf.
  • Move to the next book.
  • Repeat until there are no books left in the pile.

Example: Print even numbers from 2 to 10

for (int i = 2; i <= 10; i += 2) {
    std::cout << i << " ";
}

What happens here?

  • We begin at 2 (int i = 2)
  • Keep printing numbers as long as i is less than or equal to 10
  • Each time through, “i” becomes 2 bigger (i += 2)

i = 2 (print 2) → i = 4 (print 4) → i = 6 (print 6) → i = 8 (print 8) → i = 10 (print 10)

Output: 2 4 6 8 10

Why use a for loop?

We use "for" loop for its clarity and precision. It is designed for situations where you know exactly how many times you want to repeat an action.

By bundling the initialisation, condition, and increment (or updation) in one compact line, it simplifies the logic and makes your code cleaner, easier to read, and less prone to errors.

Having covered the C++ for loop, we now turn our attention to the C++ do-while loop.

The “do-while” Loop: Walkthrough and Examples

This loop always runs the code block at least once, even if the condition is false to begin with. It works like this: "Do this first, then check if the condition is true to repeat."

Structure of a do-while loop:

do {
    // Do something
} while (condition);

Notice how the condition comes at the end. That means the code gets a “free pass” and runs first, before checking if it should go again.

Example: Keep asking for a positive number until you get one

int number;
do {
    std::cout << "Enter a positive number: ";
    std::cin >> number;
} while (number <= 0);

Here’s how this works, even if the user types a negative number first:

  • The instructions inside the braces run at least once.
  • Afterwards, if the number entered is 0 or less, the loop repeats and asks again.
  • Once the user enters a positive number, the loop ends.

Here’s a concise dry run:

  • User enters -5: Condition check (-5 <= 0) is true, loop repeats.
  • User enters 0: Condition check (0 <= 0) is true, loop repeats.
  • User enters -2: Condition check (-2 <= 0) is true, loop repeats.
  • User enters 3: Condition check (3 <= 0) is false, loop ends.

Having understood the do-while loop, let's now focus on infinite loops.

Infinite Loops: What Are They and How Do They Happen?

Imagine a hamster running on a wheel that never stops. An infinite loop is when your loop never ends! This can crash your program or freeze your PC, so it’s important to know why they happen.

How do infinite loops happen?

  • The condition you’re using never becomes false.
  • You forgot the part where you’re supposed to update a variable.

Purposely making an infinite loop

Sometimes programmers want a loop to run forever (like a game or server that waits for requests):

while (true) {
    // Program waits or listens for input
}

Here’s an example of a purposeful infinite loop in C++, commonly used for scenarios like servers waiting for client requests:

while (true) { // Infinite loop
    cout << "Waiting for requests..." << endl;
    // Simulate processing (could be receiving data, responding to a client, etc.)
}

Explanation:

  • The condition in "while (true)" is always true, so the loop never ends.
  • This kind of loop is often paired with event handling or conditions that allow exiting when necessary (like user input or a break signal).
  • In real-world applications, you'd likely include logic to check for specific events (e.g., incoming network requests) within the loop.

Accidentally making an infinite loop

Remember to increment your loop counters! If you forget, the loop might run forever because the condition that tells it to stop depends on the counter's value changing.

Here’s a common mistake:

int i = 0;
while (i < 5) {
    std::cout << i;
    // Oops! Forgot i++ here
}

Here, because i is never incremented, i stays at 0, so the condition stays true.

Pitfall Checklist:

  1. Always double-check that the condition will eventually become false.
  2. Make sure anything you’re checking actually changes inside the loop!

Time Complexity: How Long Does Your Loop Take?

Time complexity sounds intimidating, but let’s make it simple. It’s a way to measure how much work your code is doing, especially as the amount of data grows.

What does O(n) mean?

  • "O" stands for "Order of."
  • If a loop goes over 10 items, it works 10 times = O(10).
  • If a loop goes over 1000 items, it works 1000 times = O(1000) or O(n).
  • "n" stands for the size of your data.

Simple for loop example:

for (int i = 0; i < n; ++i) {
    // Runs n times
}
  • This is called O(n) or “linear time.”

What if there are loops inside loops?

for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
        // Runs n * n times
    }
}
  • Now the inner loop repeats for each outer loop. So if n is 10, 10 x 10 = 100 times (O(n²), called “quadratic time”).

Infinite Loop Complexity

  • An infinite loop never finishes, so we say it takes "infinite time" or has “undefined” complexity.

Why care about time complexity?

  • If you write inefficient loops, your program could become slow (imagine a game that freezes or a website that loads forever).
  • Pick the right loop for the job—and avoid unnecessary "nested" (inside each other) loops whenever possible.

Expert Loop Tips You Must Know.

  • Double-check your loop conditions before you run your code.
  • Use a piece of paper (or fingers!) to “walk through” one pass of the loop.
  • If things don’t work as expected, add extra "cout "statements inside the loop to print variable values and see what’s happening!
  • Remember, loops won’t stop unless you change what you’re checking.
  • Practice: Write out a loop in plain English, then translate it to code. The more you practice, the less confusing loops will feel!

The Takeaway

That’s loops in C++, your trusty tool for making a computer do your bidding, over and over, until you say stop. With the knowledge here, you’ve got everything you need to start building your own programs, and enough detail to fix problems your loops might cause.

The best way to really "get" loops is to play around and experiment. Try changing loop conditions, add more code inside the blocks, and see what happens. You’ll become loop-savvy in no time!