🔍

Loops in Programming
For, While, Nested Loops



What are Loops in Programming?

Loops are used to execute a block of code repeatedly as long as a given condition is true. They help reduce code duplication and are essential in tasks like traversing arrays, repeating calculations, or processing input.

Why Use Loops?

Types of Loops

For Loop Example

Let’s print numbers from 1 to 5 using a for loop.

for i = 1 to 5:
    print(i)

Output:

1
2
3
4
5

How it works:

The loop starts at 1 and increments i by 1 until it reaches 5. Each time, the value of i is printed.

Question:

What happens if we change the condition to go from 5 to 1?

Answer:

You need to decrement i instead of incrementing:

for i = 5 to 1 step -1:
    print(i)

Output:

5
4
3
2
1

While Loop Example

This loop continues while a condition is true.

i = 1
while i <= 5:
    print(i)
    i = i + 1

Output:

1
2
3
4
5

Explanation:

The loop starts with i = 1. Each iteration increases i by 1. When i becomes 6, the condition i <= 5 is false, and the loop exits.

Question:

What if we forget to increment i?

Answer:

The loop will never end, resulting in an infinite loop. Always ensure there's a termination condition being met.

Do While Loop Example

This loop executes at least once, even if the condition is false.

i = 10
do:
    print(i)
    i = i + 1
while i <= 5

Output:

10

Explanation:

Even though the condition is false at the start, the loop body runs once before checking it.

Nested Loops

Loops inside loops are called nested loops. These are useful for working with 2D data like grids or matrices.

for i = 1 to 3:
    for j = 1 to 2:
        print("i =", i, ", j =", j)

Output:

i = 1 , j = 1
i = 1 , j = 2
i = 2 , j = 1
i = 2 , j = 2
i = 3 , j = 1
i = 3 , j = 2

Common Loop Pitfalls

Summary

Quick Intuition Check

Q: How many times will the following loop run?

i = 1
while i < 4:
    print(i)
    i = i + 1

A: It will print 1, 2, and 3 — 3 times in total.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M