Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 08 Beginner

Loops in C++

Updated: May 17, 2026
5 min read

# CHAPTER 8

Loops in C++

1. Introduction

Imagine needing to print "Hello" 10,000 times. Typing cout 10,000 times is impossible. Loops solve this by allowing a block of code to run repeatedly as long as a specified condition remains true. They are the backbone of automation in programming.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the for loop for iteration.
  • Use the while loop for unknown iteration counts.
  • Use the do-while loop for guaranteed first execution.
  • Manipulate loop flow using break and continue.
  • Understand nested loops.

3. The for Loop

Used when you know exactly how many times you want the loop to run.

Syntax: for (initialization; condition; increment/decrement)

cpp
12345678910
#include <iostream>
using namespace std;

int main() {
    // Prints 1 to 5
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    return 0;
}

How it works:

  1. 1. int i = 1: Executes ONCE at the start.
  1. 2. i <= 5: Checked before every loop. If true, run the code. If false, stop.
  1. 3. i++: Executes after the code block runs, then goes back to step 2.

4. The while Loop

Used when you don't know how many times the loop will run, but you know the condition that should keep it running.
cpp
123456
int count = 1;

while (count <= 5) {
    cout << count << " ";
    count++; // CRITICAL: Don't forget to update the condition!
}

5. The do-while Loop

Similar to the while loop, but it guarantees that the code block will execute at least once, because the condition is checked at the *bottom* of the loop.
cpp
12345678
int password;

do {
    cout << "Enter password (1234): ";
    cin >> password;
} while (password != 1234);

cout << "Access Granted!" << endl;

6. The break and continue Statements

  • break: Immediately terminates the loop completely.
  • continue: Skips the current iteration and jumps to the next one.
cpp
12345678910
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        continue; // Skips printing 5
    }
    if (i == 8) {
        break; // Stops the loop entirely at 8
    }
    cout << i << " ";
}
// Output: 1 2 3 4 6 7

7. Nested Loops

A loop inside a loop. The inner loop runs completely for every single iteration of the outer loop.
cpp
1234567
// Prints a 3x3 grid of stars
for (int i = 1; i <= 3; i++) {       // Outer loop (Rows)
    for (int j = 1; j <= 3; j++) {   // Inner loop (Columns)
        cout << "* ";
    }
    cout << endl; // Newline after each row
}

8. Mini Project: Pattern Generator

cpp
1234567891011121314151617
#include <iostream>
using namespace std;

int main() {
    int rows;
    cout << "Enter number of rows: ";
    cin >> rows;

    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }
        cout << endl;
    }

    return 0;
}

*Output for 4 rows:*

text
1234
1 
1 2 
1 2 3 
1 2 3 4 

9. Memory-Level Explanation

Loops do not duplicate the code in memory. The compiled machine code contains a single block of instructions with a "Jump" command at the end that points the CPU back to the top of the block until the condition register is zero.

10. Common Mistakes

  • Infinite Loops: Forgetting i++ in a while loop means the condition never becomes false, crashing/freezing the program.
  • Off-by-One Errors: Using < 5 instead of <= 5 when you actually want it to run 5 times starting from 1.
  • Semicolon after for/while: for (int i=0; i<5; i++); { cout << i; } The semicolon terminates the loop instantly, and the block below it runs only once.

11. Exercises

  1. 1. Write a while loop that counts backwards from 10 to 1, then prints "Liftoff!".
  1. 2. Write a for loop that prints all even numbers between 1 and 20.
  1. 3. Write a do-while loop that creates a simple menu system (Press 1 to Play, 2 to Quit).

12. MCQ Quiz with Answers

Question 1

Which loop is best when you know exactly how many iterations you need?

Question 2

Which loop is guaranteed to run at least once?

Question 3

What does the break statement do in a loop?

Question 4

What does the continue statement do?

Question 5

What causes an infinite loop?

Q6. Can you declare a variable inside the initialization part of a for loop? a) Yes b) No Answer: a) Yes (e.g., for (int i = 0; ...))
Question 7

What is the output of for(int i=0; i<3; i++) cout << i;?

Question 8

In a nested loop, how many times does the inner loop execute?

Question 9

Which loop evaluates its condition at the bottom?

Question 10

Is for(;;) a valid C++ statement?

13. Interview Questions

  • Q: Explain the difference between while and do-while loops.
  • Q: Write code to calculate the factorial of a number using a for loop.
  • Q: What is a "Range-based for loop" in Modern C++?

14. Summary

Loops execute code repeatedly. The for loop is ideal for known iteration counts. The while loop handles conditional repetition. The do-while loop ensures at least one execution. break and continue give fine-grained control over the loop's execution flow.

15. Next Chapter Recommendation

In Chapter 9: Functions in C++, we will learn how to group blocks of code into reusable modules, making our programs cleaner and easier to maintain.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·