Types of Loops in Programming – For, While and Do While Explained

Imagine having to print “Hello” 100 times. You could write 100 lines of code – or you could write one loop.

That is exactly what loops are for. They let you repeat a block of code as many times as you need — without writing it over and over again.

Once you understand loops, you will write cleaner, smarter, and faster code from day one.

🔁 Loops

What Is a Loop in Programming?

Coding for kids

What if you had to print “Hello” 100 times? Without a loop, that’s 100 lines of code. With a loop — it’s 2. Let me show you exactly what that means.


📖 Definition

Simple Definition

A loop is an instruction that tells your program to repeat a block of code multiple times — automatically. You write the code once, and the loop runs it again and again until you tell it to stop.

A loop repeats a block of code over and over — either a set number of times, or until a condition becomes false. That’s it. One idea, endless power.

for while do…while iteration condition
🔍 Analogy

Real-Life Analogy — Your Morning Routine

Think about your morning routine. Every single day you do the same steps — in the same order. You don’t write a new plan each morning. You just repeat it automatically.

⏰Wake up
đŸšŋShower
👕Get dressed
đŸŗBreakfast
đŸšĒLeave home
â†ē Repeat every morning
💡 That repeated routine is a loop. In code, a loop does the exact same thing — runs the same steps over and over, so you don’t have to write them out each time.
âš ī¸ The Problem

Without Loops vs With Loops

Say you want to print “Hello” five times. Without a loop, you write the same line five times. Imagine doing that for 100 or 1000 times — it becomes impossible fast.

❌ Without a Loop
print(“Hello”)
print(“Hello”)
print(“Hello”)
print(“Hello”)
print(“Hello”)
# 5 lines for 5 prints
# 1000 prints = 1000 lines 😩
✅ With a Loop
for i in range(5):
  print(“Hello”)

# Just 2 lines
# Change 5 to 1000?
# Still just 2 lines ✓
Loops are how programmers avoid repeating themselves. Write it once, run it as many times as you need. That single idea saves thousands of lines of code every day.
🔁 For Loop

The For Loop — When You Know How Many Times

The most common loop — perfect when the count is fixed.

The for loop is the most common loop in coding. Use it when you know exactly how many times you want something to repeat.

⚡ JavaScript

For Loop in JavaScript

⚡ forloop.js
for (let i = 0; i < 5; i++) {
  console.log(i);
}
Output→ 0   1   2   3   4
🐍 Python

For Loop in Python

Python’s for loop is even cleaner — no counter setup needed. Just use range() to tell it how many times.

🐍 forloop.py
for i in range(5):
  print(i) # 0, 1, 2, 3, 4
Output→ 0   1   2   3   4
⚡ JavaScript
Uses let i = 0, condition, and i++ — manual setup
🐍 Python
Uses range(n) — cleaner, automatic counter
🔍 Breakdown

Breaking Down the For Loop

The JavaScript for loop has three parts inside the brackets — each one has a specific job.

🔍 for ( start ; condition ; update )
let i = 0
Start
Where the counter begins
i < 5
Condition
Keep running while true
i++
Update
What to do after each run
for (let i = 0; i < 5; i++) {
  console.log(i);
}
① Start: i = 0
→
② Check: i < 5?
→
â‘ĸ Run code
→
â‘Ŗ Update: i++
→
② Check againâ€Ļ
🔄 While Loop

The While Loop — When You Don’t Know How Many Times

A for loop is great when you know the count. But what if you don’t? What if you want to keep going until something happens? That’s exactly what the while loop is for.


đŸ‘ī¸ How It Works

A while loop checks a condition first. If it’s true — it runs the code. Then checks again. And keeps going until the condition turns false.

â–ļ Start
↓
❓ Is condition true?
YES
↓
âš™ī¸ Run the code block
â†ē Go back and check condition again
NO
↓
🛑 Stop — exit the loop

While Loop in JavaScript + Python

Same idea in both — keep running while the condition stays true. Count up to 5 and stop.

⚡ JavaScript
let i = 1;
while (i <= 5) {
  console.log(i);
  i++; // ← must update!
}
// OUTPUT → 1 2 3 4 5
🐍 Python
i = 1
while i <= 5:
  print(i)
  i += 1 # ← must update!

# OUTPUT → 1 2 3 4 5
âš ī¸

Watch out — Infinite Loop! If you forget to update i, the condition never turns false and your loop runs forever — crashing your program. Always make sure your loop has a way to stop.

📊 For vs While

For vs While — When to Use Which

SituationBest LoopExample
You know the exact countfor loopPrint numbers 1–10
Loop through a listfor loopGo through every item in an array
You don’t know when it stopswhile loopKeep asking until user types “quit”
Waiting for a conditionwhile loopKeep retrying until connection succeeds
Simple rule: know the count → use for. Don’t know the count → use while. When in doubt, for loops are the safer choice for beginners.
🔁 Do/While

The Do/While Loop — Run at Least Once

The do/while loop is the least common — but it solves one specific problem perfectly: what if you need the code to run at least once, no matter what?


âš–ī¸ Key Difference

The only difference between while and do/while is when the condition is checked. While checks first — do/while runs first, then checks.

while loop
❓ Check condition first
↓ if true
âš™ī¸ Run code
↓
🛑 Stop if false
May never run
do/while loop
âš™ī¸ Run code first
↓
❓ Now check condition
↓ if false
🛑 Stop
Always runs at least once
⚡ JavaScript

Do/While in JavaScript

The do block runs first. Then the while condition is checked. If false — it stops. Here is a classic example: asking for a password until the user gets it right.

⚡ password.js
let password;

do {
  password = prompt(“Enter password:”);
} while (password !== “secret123”);

console.log(“Access granted!”);
// Always asks at least once ✓
// Keeps asking until correct ✓
🔐 Why do/while here? You always need to ask for the password at least once. A regular while loop would need the password before it even starts — which makes no sense. Do/while fits perfectly.
📋 When to Use

When to Use Do/While

✅ Good fit for:

✅ Asking for user input at least once
✅ Menu systems — show menu, then decide
✅ When the first run must always happen

❌ Not ideal when:

❌ You know the count in advance
❌ The first run might not be needed
❌ Looping through a list or array
Do/while is the rarest loop — but when you need it, nothing else fits. As a beginner, master for and while first. Come back to do/while when you hit a situation where the first run must always happen.
⭐ Arrays + Loops

Looping Through Arrays

This is where loops become truly powerful. Going through every item in a list — one by one — is something you’ll do in almost every program you ever write.


⚡ Classic Way

Classic For Loop with Arrays

The classic approach uses an index counter i to step through each slot in the array — starting at 0, ending at the last item.

“Ali”i=0
“Sara”i=1
“Hamza”i=2
“Zara”i=3
↑ loop starts here
ends here ↑
⚡ classic.js
let names = [“Ali”, “Sara”, “Hamza”, “Zara”];

for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}
// OUTPUT → Ali Sara Hamza Zara
✨ Cleaner Way

for…of — The Cleaner Way ✅ Recommended

The for...of loop is the modern, cleaner way to loop through arrays in JavaScript. No index counter needed — it just grabs each value directly.

⚡ forof.js
let names = [“Ali”, “Sara”, “Hamza”, “Zara”];

for (let name of names) {
  console.log(name); // each value directly
}
// OUTPUT → Ali Sara Hamza Zara
loop 1→“Ali”first item
loop 2→“Sara”second item
loop 3→“Hamza”third item
loop 4→“Zara”last item → done
🐍 Python

Python for Loop with Lists

Python’s for loop is even simpler. It works directly on lists — no index, no length check. Just loop through each item naturally.

🐍 loop.py
names = [“Ali”, “Sara”, “Hamza”, “Zara”]

for name in names:
  print(name)

# OUTPUT → Ali Sara Hamza Zara
💡 Python’s for loop is the cleanest of all. No i, no length, no brackets. Just for item in list — and Python handles the rest automatically.
Looping through arrays is something you’ll do every single day as a developer. In JavaScript, use for...of for clean code. In Python, just use for item in list — it’s that simple.
âšī¸ Control

Break and Continue — Controlling Loops

Sometimes you need to stop a loop early. Other times you want to skip one item and move on. That’s exactly what break and continue are for.


âšī¸ Break

What Does Break Do?

break stops the loop completely — right where it is. The moment the program hits break, it exits the loop and moves on.

1runs ✓
2runs ✓
3runs ✓
4BREAK ✗
5skipped
Runs normally
Break fires here
Never reached
⚡ JavaScript
for (let i = 1; i <= 5; i++) {
  if (i === 4) break; // stop at 4
  console.log(i);
}
// OUTPUT → 1 2 3
â­ī¸ Continue

What Does Continue Do?

continue skips the current item and jumps straight to the next one. The loop keeps going — it just skips whatever you tell it to skip.

1runs ✓
2runs ✓
3SKIP â¤ĩ
4runs ✓
5runs ✓
Runs normally
Skipped by continue
⚡ JavaScript
for (let i = 1; i <= 5; i++) {
  if (i === 3) continue; // skip 3
  console.log(i);
}
// OUTPUT → 1 2 4 5
🐍 Python Examples

Code Examples in Python

🐍 Python — break
for i in range(1, 6):
  if i == 4:
    break
  print(i)
# OUTPUT → 1 2 3
🐍 Python — continue
for i in range(1, 6):
  if i == 3:
    continue
  print(i)
# OUTPUT → 1 2 4 5
break

Exits the entire loop immediately. Nothing after it runs in this loop.

continue

Skips only the current item. Loop continues with the next one.

Memory trick: break = exit the whole loop. continue = skip this one, keep going. Same syntax in JS and Python — only the colon vs curly braces differ.
🔄 Patterns

Common Loop Patterns Every Beginner Should Know

These three patterns show up in real projects constantly. Once you know them, you’ll recognize them everywhere — and writing loops will start to feel natural.


➕
Pattern 1

Sum All Numbers in a List

Start with a total of 0. Loop through each number and add it to the total. Common use: calculating a shopping cart total, averaging scores.

1
Create a sum variable set to 0
2
Loop through each number — add it to sum
3
After loop — print the final sum
numbers = [10, 20, 30, 40]
total = 0 # start at 0

for num in numbers:
  total += num # add each number

print(total)
let numbers = [10, 20, 30, 40];
let total = 0; // start at 0

for (let num of numbers) {
  total += num; // add each number
}
console.log(total);
OUTPUT → 100 (10 + 20 + 30 + 40)
🔍
Pattern 2

Find an Item in a List

Loop through each item and check if it matches what you’re looking for. When found — print it and stop with break. Common use: searching for a user, product, or name.

1
Loop through every item in the list
2
Check if current item matches your target
3
If yes — print it and break out of loop
names = [“Ali”, “Sara”, “Hamza”, “Zara”]

for name in names:
  if name == “Hamza”:
    print(“Found:”, name)
    break
let names = [“Ali”, “Sara”, “Hamza”, “Zara”];

for (let name of names) {
  if (name === “Hamza”) {
    console.log(“Found:”, name);
    break;
  }
}
OUTPUT → Found: Hamza loop stops immediately after
đŸ”ĸ
Pattern 3

Count How Many Times Something Appears

Start a counter at 0. Loop through the list and add 1 every time you find a match. Common use: counting votes, occurrences, or how many items pass a condition.

1
Set a count variable to 0
2
Loop through every item — check the condition
3
If condition is true — add 1 to count
scores = [85, 42, 91, 55, 78]
count = 0 # start counting at 0

for score in scores:
  if score >= 70: # passing score?
    count += 1

print(“Passed:”, count)
let scores = [85, 42, 91, 55, 78];
let count = 0; // start counting at 0

for (let score of scores) {
  if (score >= 70) { // passing score?
    count++;
  }
}
console.log(“Passed:”, count);
OUTPUT → Passed: 3 (85, 91, 78 are â‰Ĩ 70)
Sum, find, count — these three patterns cover most of what loops are used for in real projects. Learn these and you will recognize the same structure in almost every loop you ever read or write.
❓ FAQs

FAQs About Loops

Three questions beginners always ask about loops — answered simply and clearly.


Q1

What is the most common loop in programming?

â–ŧ

The for loop is by far the most used loop in programming. Most tasks involve repeating something a known number of times — or going through every item in a list — and the for loop handles both perfectly.

for
Most
while
Common
do-while
Rare
As a beginner, master the for loop first. It will cover 80–90% of everything you need. Once comfortable, while becomes your second tool — and do-while a specialty you reach for rarely.
Q2

What is an infinite loop?

â–ŧ

An infinite loop is a loop that never stops — because its condition never turns false. It keeps running forever, eventually freezing or crashing your program.

âš ī¸ INFINITE LOOP — Never stops!
// JavaScript — condition is always true
while (true) {
  console.log(“Help! I can’t stop!”);
}

# Python — forgot to update i
i = 1
while i < 5:
  print(i)
  # i never updates → runs forever!
âš ī¸

Two most common causes: condition is always true, or you forgot to update the counter variable so the condition never changes.

✅

Fix: always make sure your loop has a clear exit. Update i inside while loops. If your program freezes — press Ctrl + C to stop it.

Q3

What is the difference between break and continue?

â–ŧ

Both control how a loop runs — but they do opposite things. break ends the loop entirely. continue only skips the current item and keeps the loop going.

âšī¸ break
❌ Exits the entire loop
❌ Nothing after it runs in loop
✅ Use when you found what you need
if i == 3:
  break
# loop ends here
â­ī¸ continue
â­ī¸ Skips only current item
✅ Loop keeps running after
✅ Use to skip unwanted items
if i == 3:
  continue
# jumps to next item
break vs continue exit entirely vs skip one and keep going
Memory trick: break = quit the whole loop. continue = skip this round, play on. Think of it like a game — break walks off the field, continue just skips a turn.