Quick answer
C++ has four loops: for, while, do-while and range-based for. Use for when you know the repeat count, while when a condition decides, do-while when the body must run at least once, and range-based for to visit every item in an array or vector. Most beginner bugs are off-by-one errors and infinite loops.
Key takeaways
- • C++ has four iteration statements: for, while, do-while and the C++11 range-based for.
- • for and while check the condition before each pass; do-while checks after, so it always runs once.
- • Ask three questions in order: every item in a container, known count, must run once. Otherwise use while.
- • Off-by-one errors, stray semicolons, missing updates, != counters and unsigned countdowns cause most loop bugs.
- • Trace the first two and last two passes by hand before you run any loop.
Table of contents 15 sections
- What Are Loops in C++, and Why Does Every Course Start With Them?
- The Four Loops in C++ Side by Side
- How Does the for Loop in C++ Work?
- Small Details That Change the Output
- The while Loop: Repeat Until Something Changes
- The do-while Loop: Run First, Check Later
- Range-Based for: The Easy Way Through Arrays and Vectors
- Which Loop Should You Use?
- break, continue and Nested Loops
- Loops Inside Loops
- Why Does My Loop Never Stop? Five Common Bugs
- Practice Programs From Easy to Exam Level
- Do Loops Work the Same Way in Other Languages?
- How PSTA's C++ Course Teaches Loops
- Your Homework: Rewrite One Loop Three Ways
Loops in C++ come in four kinds, and Microsoft's C++ language reference lists exactly four iteration statements: while, do, for and the range-based for. Each one repeats a block of code, but they differ in when the condition is checked and who manages the counter. Pick the right one and your program reads like a sentence. Pick the wrong one and you spend your lab hour hunting a loop that never ends.
In this guide you'll find:
- How each of the four loops runs, step by step, with short programs you can type and test
- A simple way to decide which loop fits a problem before you write a line
- What
break,continueand nested loops actually do - The five loop bugs that cost students the most marks in labs and exams
- A graded set of practice programs, from a times table to a pattern printer
What Are Loops in C++, and Why Does Every Course Start With Them?
A loop tells the computer to repeat some statements while a condition stays true. Without loops, printing the numbers 1 to 100 would take 100 separate lines. With a loop it takes three.
That's why loops show up so early in Pakistani university courses. NED University's CS-109 Computer Programming lab workbook gives for loops and nesting their own lab session, then covers while and do-while in the next one. A CS1202 Computer Programming outline on the University of the Punjab website places while, for, do-while, break and continue in Unit 3, right after decisions with if and switch. Arrays, functions and pointers all come later, and almost every one of them uses a loop.
C++ also remains a language worth the effort. In the TIOBE index for November 2026, C++ sits fourth with a rating of 8.35%, behind Python, C and Java.
The Four Loops in C++ Side by Side
Before the details, here is the whole family in one table. The "condition checked" column is the one that matters most for exams.
| Loop | Condition Checked | Runs at Least Once? | Best For |
|---|---|---|---|
for |
Before each pass | No | A known number of repeats, such as 1 to 10 |
while |
Before each pass | No | Repeating until something changes, such as reading input until 0 |
do-while |
After each pass | Yes | Menus and input checks that must show at least once |
Range-based for |
Before each element | No (an empty container skips it) | Visiting every item in an array, vector or string |
The first three are classic loops that every C++ textbook covers. The fourth arrived with C++11 and is the one modern code uses most when walking through a container.
How Does the for Loop in C++ Work?
A for loop packs three parts into one line: a starting value, a condition and an update. Here is the classic example that prints a times table.
#include <iostream>
using namespace std;
int main() {
int n = 7;
for (int i = 1; i <= 10; i++) {
cout << n << " x " << i << " = " << n * i << endl;
}
return 0;
}
The order of execution is fixed, and Learn C++ describes it the same way most teachers draw it on the board:
- The start part (
int i = 1) runs once. - The condition (
i <= 10) is checked. If it's false, the loop ends. - The body runs.
- The update (
i++) runs, and control jumps back to step 2.
Notice that the update runs after the body, not before. Students who get this wrong usually predict the output starting at 2 instead of 1.
Small Details That Change the Output
A variable declared inside the brackets, like int i, exists only inside the loop. Try to print i after the closing brace and the compiler stops you. Any of the three parts can be left empty, so for (;;) is legal and runs forever unless something inside breaks out. You can also manage two counters at once, for example for (int i = 0, j = 9; i < j; i++, j--), which is handy for reversing an array in place.
The while Loop: Repeat Until Something Changes
Use a while loop in C++ when you don't know in advance how many times the body will run. The condition sits at the top, so if it's false at the start, the body never runs at all.
int number, sum = 0;
cout << "Enter numbers (0 to stop): ";
cin >> number;
while (number != 0) {
sum += number;
cin >> number;
}
cout << "Total: " << sum << endl;
Here the stopping point depends on the user, not on a counter. That's the signal to reach for while. Another common case is digit work: counting or reversing the digits of a number with while (n > 0) { ... n /= 10; }. You can't know the digit count before you start, so a counting loop would feel forced.
One rule keeps a while loop safe: something inside the body must move the condition toward false. In the example above, that job belongs to the second cin. Remove it and the loop adds the same number forever.
The do-while Loop: Run First, Check Later
A do-while loop in C++ flips the order. The body runs first and the condition is checked at the bottom, which Microsoft's summary table states plainly. The result is a loop that always runs at least once.
int choice;
do {
cout << "1. Deposit 2. Withdraw 3. Exit" << endl;
cout << "Choose: ";
cin >> choice;
} while (choice != 3);
A menu is the textbook use, because you want the options on screen before you can ask whether the user is done. Input checks work the same way: ask for marks, then repeat the question while the value is below 0 or above 100.
Two small things trip people up. The line ends with a semicolon after the closing bracket, } while (choice != 3);, and forgetting it is a compile error. And any variable used in the condition must be declared before do, not inside the braces, or the condition can't see it.
Range-Based for: The Easy Way Through Arrays and Vectors
Since C++11, a range-based for loop lets you walk through every element of a container without managing an index at all. The colon reads as "in".
#include <vector>
vector<int> marks = {72, 85, 64, 91, 58};
int total = 0;
for (const auto& m : marks) {
total += m;
}
cout << "Average: " << total / 5.0 << endl;
The Learn C++ lesson on range-based for loops recommends preferring this form over a counting loop when you simply visit every element. It also explains the three ways to write the element variable:
auto mgives you a copy of each element. Fine for small types likeint.auto& mgives you the real element, so changes you make stick.const auto& mlets you read without copying, which matters for strings and large objects.
The trade-off is that you don't get an index. If your output needs "Student 3 scored 64", either keep your own counter or switch back to a classic for. If you already use vectors and maps, our guide to the STL in C++ shows where this loop fits with containers and algorithms.
Which Loop Should You Use?
Most of the time the problem statement tells you. Ask three questions in order:
- Am I visiting every item in an array, vector or string? Use range-based
for, unless you need the position. - Do I know how many times to repeat before starting? "Print the first 20 even numbers" or "sum 1 to n" means a classic
for. - Must the body run at least once? Menus and "enter a valid value" checks suit
do-while. Everything else, where a condition decides and zero runs is acceptable, suitswhile.
Any loop can be rewritten as any other, and examiners like to ask for exactly that conversion. Readability is the real test. Learn C++ gives a sensible rule of thumb: use for when there's an obvious counter and while when there isn't.
break, continue and Nested Loops
Two keywords give you finer control, and break and continue in C++ behave the same way inside all four loop types. break leaves the nearest loop immediately. continue skips the rest of the current pass and moves to the next one. A prime-number check shows break well:
bool isPrime = (n > 1);
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break; // no need to test more divisors
}
}
Use continue to skip values you don't want, such as ignoring negative entries while adding up a list. Keep both rare, though. A loop with three break statements is usually a sign that the condition at the top should be rewritten.
Loops Inside Loops
Nested loops in C++ run the inner loop completely for every single pass of the outer one. That's how you print a star triangle, a multiplication grid or a 2D matrix:
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
cout << "* ";
}
cout << endl;
}
Work out the cost before you nest. An outer loop of 1,000 and an inner loop of 1,000 means a million passes. One break also exits only the inner loop, not both, a detail that shows up often in viva questions.
Why Does My Loop Never Stop? Five Common Bugs
These are the loop mistakes we correct most in beginner C++ classes. Each one compiles without a warning, which is what makes them annoying.
- Off-by-one errors. Writing
i < 10when you meanti <= 10prints nine values instead of ten. With arrays it's the reverse: an array of 5 has indexes 0 to 4, soi <= 5reads past the end. - A stray semicolon.
for (int i = 0; i < 5; i++);ends the loop at the semicolon. The braces below then run once, and the output looks like the loop "skipped" its work. - Forgetting the update. A
whileloop that never changes its own condition becomes an infinite loop. Before you run, point to the line that moves the condition toward false. - Using
!=with a counter. Learn C++ advises<or<=for numeric conditions. Withi += 2starting at 1, the testi != 10is never false, becauseijumps from 9 to 11. - Counting down with
unsigned. An unsigned variable can never go below zero, sofor (unsigned i = 5; i >= 0; i--)wraps around to a huge number and keeps going. Useintfor countdowns.
The fastest way to catch all five is to trace the first two and the last two passes by hand, writing the value of each variable in a small table. The C++ interview questions guide has more output-prediction practice of this kind.
Practice Programs From Easy to Exam Level
Reading about loops in C++ won't make them stick. Typing them will. Work through these in order and don't move up until the current level runs correctly on the first try.
| Level | Program | Loop to Use | What It Tests |
|---|---|---|---|
| 1 | Print 1 to 50, then 50 down to 1 | for |
Start, condition and update |
| 2 | Sum and average of n numbers entered by the user | for |
Accumulator variables |
| 3 | Count the digits of a number and reverse it | while |
Unknown repeat count, % and / |
| 4 | ATM-style menu that repeats until Exit | do-while |
Run-at-least-once logic |
| 5 | Highest and lowest marks in a vector | Range-based for |
Reading every element safely |
| 6 | Prime numbers between 1 and 100 | Nested for with break |
Early exit and efficiency |
| 7 | Star pyramid with n rows | Nested for |
Linking the inner count to the outer one |
Once these feel easy, combine them into a bigger program. The ideas in our list of C++ projects for beginners lean on loops heavily, and a working project shows far more than a page of solved exercises. If you haven't set up a compiler yet, start with running C++ in VS Code.
Do Loops Work the Same Way in Other Languages?
The ideas behind loops in C++ transfer almost directly. JavaScript and Java share C++'s for, while and do-while syntax, so learning them here saves time later. Python has no do-while and its for works like C++'s range-based version, walking through items rather than counting by hand. If you're still choosing a first language, our comparison of C++ vs Python for beginners covers the trade-offs.
How PSTA's C++ Course Teaches Loops
In the PSTA C++ programming course for beginners, loops in C++ get their own unit: Module 4, "Repeating Tasks", comes right after decision-making with if and else and before functions and arrays. The whole program lasts 12 weeks, is pitched at complete beginners and finishes with a small project you write from scratch.
- Fee: Rs. 12,000 (listed down from Rs. 16,000 on the course page at the time of writing)
- Format: on campus in Abbottabad, live online from anywhere in Pakistan, or a mix of both
- Timing: a new batch starts each month, with classes between 9:00 AM and 9:30 PM, Monday to Saturday
- Who joins: Matric and FSc students preparing for BSCS or BSSE, and university students from other fields
If C++ is your first step toward software work, the Advanced Python course and the one-year DIT diploma are common next moves. You can compare fees on the full course list, fill in the admission form, or ask about the next batch on WhatsApp at +92 314 5424399. The campus is in Mandian, on Old College Road opposite FIMS College.
Your Homework: Rewrite One Loop Three Ways
Take the times-table program from the for section and rewrite it as a while loop, then as a do-while. Run all three and confirm the output matches line for line. Then change the starting value so the condition is false from the beginning and run them again. The one that still prints a line is your do-while, and you'll never mix up "checked before" and "checked after" in an exam again.
Frequently asked questions
What are the types of loops in C++?
C++ has four loops: for, while, do-while and the range-based for added in C++11. The for and while loops check their condition before each pass, so they may run zero times. The do-while loop checks after the body and always runs once. The range-based for visits each element of an array, vector or string without an index.
What is the difference between while and do-while in C++?
A while loop tests its condition at the top, so if the condition is false at the start, the body never runs. A do-while loop runs the body first and tests at the bottom, so it always runs at least once. That makes do-while the natural choice for menus and for asking the user again until the input is valid.
When should I use a for loop instead of a while loop?
Use a for loop when there is an obvious counter and you know how many passes you need, such as printing 1 to 100 or reading 10 marks. Use while when an event decides the end, such as the user typing 0 or a number running out of digits. Both can do the same job, so choose the one that reads more clearly.
Why is my C++ loop running forever?
An infinite loop usually means nothing inside the body moves the condition toward false. Check that the counter is updated, that you used < or
What does break do inside a nested loop?
break exits only the loop it sits in. Inside a nested loop it stops the inner loop, and the outer loop carries on with its next pass. If you need to leave both loops, set a flag variable and check it in the outer condition, or move the loops into a function and return from it.
Is the range-based for loop available in Turbo C++?
No. The range-based for loop arrived with the C++11 standard, and very old compilers such as Turbo C++ predate it. Use a current compiler like GCC, Clang or Microsoft Visual C++, through Code::Blocks, Visual Studio or VS Code, so that modern loop syntax and the rest of the standard library work as expected.
How many loop questions come in a programming fundamentals exam?
It varies by university and teacher, but loops are usually tested in several ways: predicting output, converting one loop type into another, and writing short programs such as primes, digit reversal or star patterns. Course outlines from NED and the University of the Punjab place loops early, so expect them in quizzes, labs and finals.
Sources & references
- Iteration Statements (C++)
- for loop
- 8.10 For statements
- 16.8 Range-based for loops (for-each)
- CS-109 Computer Programming Workbook
- CS1202 Computer Programming Course Outline
- TIOBE Index November 2026
Last reviewed & updated on by Umar Qureshi. Written by the PSTA team in Abbottabad, Pakistan.
Best C++ Programming Course for Beginners in Pakistan
Turn this guide into a career: hands-on training with real projects, online across Pakistan or on-campus in Abbottabad · 12 Weeks.
Comments
No comments yet — ask a question or share your experience.