Programming BasicsBasicsbeginner

Loops in Programming Explained with Examples

Learn for, while and do-while loops with step-by-step trace tables, Java and Python code, and the mistakes beginners make.

Published
TL;DR – Quick Answer

A loop repeats a block of code while a condition is true. Use a for loop when you know how many times to repeat, a while loop when you repeat until something happens, and a do-while loop when the body must run at least once. Every loop needs a condition that eventually becomes false.

On This Page

A loop tells the computer to repeat some work. Without loops, printing the numbers 1 to 100 would take 100 lines of code. With a loop it takes three.

This page explains the three main loops, for, while and do-while, with Java and Python code. Each loop has a trace table that shows what happens in every round, so you can follow it step by step.

What is a loop

Think of a teacher taking attendance. She does not write separate instructions for each student. She follows one rule: "Call the next roll number, mark present or absent, and repeat until the last roll number."

A loop has the same parts:

Part Attendance example In code
Start Begin at roll number 1 i = 1
Condition Continue while roll number is 60 or less i <= 60
Body Call the name and mark attendance The code inside the loop
Update Move to the next roll number i++ or i += 1

Each run of the body is called an iteration.

The for loop

Use a for loop when you know how many times to repeat.

Java

public class ForDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Round " + i);
        }
    }
}

Python

for i in range(1, 6):
    print("Round", i)

Output (same words in both):

Round 1
Round 2
Round 3
Round 4
Round 5

In Java, the three parts sit in one line: int i = 1 (start), i <= 5 (condition), i++ (update). In Python, range(1, 6) gives the numbers 1, 2, 3, 4, 5. The end value 6 is not included. This is a common source of confusion.

Here is a for loop that adds the numbers 1 to 5, with its trace table.

public class SumDemo {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum = sum + i;
        }
        System.out.println("Sum = " + sum);
    }
}
Iteration i Is i <= 5? sum after body
1 1 Yes 1
2 2 Yes 3
3 3 Yes 6
4 4 Yes 10
5 5 Yes 15
- 6 No, loop ends 15

Output:

Sum = 15

Python can also loop directly over the items of a list, which is very common:

cities = ["Hyderabad", "Pune", "Chennai"]
for city in cities:
    print(city.upper())

Output:

HYDERABAD
PUNE
CHENNAI

The while loop

Use a while loop when you do not know in advance how many times to repeat. It keeps going while its condition is true.

This example counts how many digits a number has. We do not know the count before we start, so while fits well.

Java

public class DigitCount {
    public static void main(String[] args) {
        int n = 4096;
        int count = 0;
        while (n > 0) {
            n = n / 10;
            count++;
        }
        System.out.println("Digits = " + count);
    }
}

Python

n = 4096
count = 0
while n > 0:
    n = n // 10
    count += 1
print("Digits =", count)
Iteration n before Is n > 0? n after body count
1 4096 Yes 409 1
2 409 Yes 40 2
3 40 Yes 4 3
4 4 Yes 0 4
- 0 No, loop ends - 4

Output:

Digits = 4

Each round removes the last digit by dividing by 10. When nothing is left, n becomes 0 and the loop stops. The same idea is used in counting the digits of a number.

Common mistake: If you forget the line n = n / 10, the value of n never changes. The condition stays true forever and you get an infinite loop. Press Ctrl+C in the terminal to stop it.

The do-while loop

A do-while loop runs the body first and checks the condition after. So the body always runs at least once, even if the condition is false from the start. Java, C and C++ have it. Python does not.

A menu is the classic use. You must show the menu once before you know whether the user wants to exit.

Java

public class DoWhileDemo {
    public static void main(String[] args) {
        int i = 10;
        do {
            System.out.println("Value: " + i);
            i++;
        } while (i <= 5);
        System.out.println("Done");
    }
}

Output:

Value: 10
Done

The condition i <= 5 is false from the start, but the body still ran once. A while loop with the same condition would print only "Done".

Python version of the same idea

i = 10
while True:
    print("Value:", i)
    i += 1
    if not (i <= 5):
        break
print("Done")

The output is the same. while True starts an endless loop, and the break at the end checks the condition after the body, just like do-while.

for vs while vs do-while

Point for while do-while
Best when You know the number of repeats You repeat until something happens The body must run at least once
Condition checked Before each round Before each round After each round
Minimum runs 0 0 1
Example Print a table of 7 Read input until the user types exit Show a menu
In Python? Yes Yes No (use while True with break)

Any for loop can be written as a while loop and the other way around. Pick the one that makes your code easiest to read.

break and continue

break leaves the loop at once. continue skips the rest of this round and moves to the next round.

for n in range(1, 11):
    if n % 2 == 0:
        continue      # skip even numbers
    if n > 7:
        break         # stop completely after 7
    print(n)

Output:

1
3
5
7

Even numbers are skipped by continue. When n reaches 9, which is odd and greater than 7, break ends the loop. Java uses the same two keywords with the same meaning.

Nested loops

A loop inside another loop is called a nested loop. For each round of the outer loop, the inner loop runs fully.

public class NestedDemo {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

*
* *
* * *

Row 1 prints one star, row 2 prints two, row 3 prints three. Pattern programs in placement tests are built this way. (Each line actually ends with a space after the last star, which you cannot see.)

Common beginner mistakes with loops

Mistake Example What happens Fix
Forgetting the update while (i <= 5) with no i++ Infinite loop Change the loop variable inside the body
Off-by-one for (int i = 0; i <= 5; i++) when you want 5 rounds Runs 6 times Use i < 5, or start from 1
Wrong range end in Python range(1, 5) to print 1 to 5 Prints 1 to 4 Use range(1, 6)
Semicolon after for in Java for (int i = 0; i < 5; i++); The loop has an empty body; the block below runs once, or fails to compile if it uses i Remove the semicolon
Changing a list while looping over it Removing items inside for item in items Items get skipped Loop over a copy or build a new list

Practice tasks

  1. Print the multiplication table of any number from 1 to 10.
  2. Print all even numbers from 1 to 50.
  3. Find the sum of the digits of 5274 using a while loop. The answer is 18.
  4. Print the first 10 terms of the Fibonacci series.
  5. Print a right-angled triangle of numbers using nested loops.

What to learn next

Loops become really useful with arrays, where one loop can visit hundreds of values. Read what is an array next. For Java-specific details such as the enhanced for loop, see loops in Java. If you are learning C, the same three loops appear in learn C programming step by step.

Frequently Asked Questions

What is the difference between a for loop and a while loop?
A for loop keeps the start value, condition and update in one line, so it suits a known number of repeats. A while loop only has a condition, so it suits repeating until an event, such as the user typing exit.
What is an infinite loop?
It is a loop whose condition never becomes false, so it never stops. It usually happens when you forget to update the loop variable. Press Ctrl+C in the terminal to stop such a program.
Does Python have a do-while loop?
No. Python has only for and while. You can get the same effect with while True and a break at the end of the body.
What do break and continue do?
break stops the loop completely and moves to the code after it. continue skips the rest of the current round and jumps to the next one.
How many times does a nested loop run?
Multiply the counts. If the outer loop runs 3 times and the inner loop runs 4 times for each outer round, the inner body runs 3 x 4 = 12 times.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — View the Java Full Stack curriculum

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 4 December 2026 LinkedIn
Chat with us