Computer Science

Nested Loops in Python | Notes, Flowcharts, Examples & Pattern Programs | CBSE Class 11 Computer Science

Class 11 · Computer Science

Nested Loops in Python

A Nested Loop is a loop placed inside another loop. The outer loop controls how many times the inner loop executes. Nested loops are widely used for solving problems involving patterns, multiplication tables, matrices, grids, and two-dimensional data.


Learning Objectives

  • Understand the concept of nested loops.
  • Use nested for loops.
  • Use nested while loops.
  • Understand the execution flow of nested loops.
  • Develop logic for solving pattern-based problems.

What is a Nested Loop?

A Nested Loop means writing one loop inside another loop.

The loop containing another loop is called the Outer Loop, while the loop inside it is called the Inner Loop.

For every iteration of the outer loop, the inner loop executes completely.


Syntax

Nested for Loop

for i in range(...):
    for j in range(...):
        statements

Nested while Loop

i=1
while i<=3:
    j=1
    while j<=3:
        statements
        j=j+1
    i=i+1

Working of Nested Loops

  1. The outer loop starts.
  2. The inner loop executes completely.
  3. The outer loop moves to the next iteration.
  4. The inner loop starts again from the beginning.
  5. This continues until the outer loop finishes.

Flowchart

          Start
             |
      Outer Loop Begins
             |
      Inner Loop Begins
             |
      Execute Statements
             |
   Inner Loop Completed?
        /          \
      No            Yes
      |              |
Repeat Inner     Next Outer
Loop Iteration   Iteration
             |
      Outer Loop Finished?
        /          \
      No            Yes
      |              |
Repeat Outer       End
Loop

Example 1: Print Coordinates

for i in range(1,4):
    for j in range(1,4):
        print(i,j)

Output

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Example 2: Multiplication Table (1 to 3)

for i in range(1,4):
    print("Table of",i)
    for j in range(1,11):
        print(i,"x",j,"=",i*j)

Example 3: Nested while Loop

i=1
while i<=3:
    j=1
    while j<=3:
        print(i,j)
        j=j+1
    i=i+1

Example 4: Print Rectangle Pattern

for i in range(4):
    for j in range(5):
        print("*",end=" ")
    print()

Output

* * * * *
* * * * *
* * * * *
* * * * *

Example 5: Number Pattern

for i in range(1,6):
    for j in range(1,6):
        print(j,end=" ")
    print()

Output

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Dry Run

Program

for i in range(1,3):
    for j in range(1,3):
        print(i,j)
Outer Loop (i) Inner Loop (j) Output
1 1 1 1
1 2 1 2
2 1 2 1
2 2 2 2

Real-Life Applications

  • Generating seating arrangements.
  • Printing multiplication tables.
  • Creating calendars.
  • Processing matrices.
  • Game board programming.
  • Generating reports.
  • Drawing patterns.
  • Image processing.

Pattern Programs

1. Square Star Pattern

for i in range(5):
    for j in range(5):
        print("*",end=" ")
    print()

Output

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

2. Right Triangle Pattern

for i in range(1,6):
    for j in range(i):
        print("*",end=" ")
    print()

Output

*
* *
* * *
* * * *
* * * * *

3. Number Triangle

for i in range(1,6):
    for j in range(1,i+1):
        print(j,end=" ")
    print()

Output

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Advantages of Nested Loops

  • Useful for solving complex problems.
  • Helps in matrix operations.
  • Required for pattern generation.
  • Improves logical thinking.
  • Supports multidimensional data processing.

Common Programming Mistakes

1. Incorrect Indentation

for i in range(3):
for j in range(3):
    print(i,j)

Explanation: Proper indentation is mandatory.


2. Using the Same Variable Name

Wrong

for i in range(3):
    for i in range(3):
        print(i)

Explanation: Always use different variables such as i and j.


3. Forgetting to Reset Inner Loop Variable (while Loop)

In nested while loops, the inner loop variable must be re-initialized during each iteration of the outer loop.


CBSE Important Programs

  1. Rectangle Pattern
  2. Square Pattern
  3. Right Triangle Pattern
  4. Inverted Triangle
  5. Number Triangle
  6. Multiplication Tables
  7. Coordinate Printing
  8. Chessboard Pattern
  9. Simple Matrix Display
  10. Alphabet Pattern

Viva Questions

  1. What is a nested loop?
  2. What is the difference between the outer loop and inner loop?
  3. How many times does the inner loop execute?
  4. Can a for loop be nested inside a while loop?
  5. Can a while loop be nested inside a for loop?
  6. Which variable is generally used for the outer loop?
  7. Why are nested loops used in pattern programs?
  8. Can nested loops create infinite loops?
  9. Give two applications of nested loops.
  10. What happens if the inner loop is not reset in a nested while loop?

Exam Tips

  • Use different variables for outer and inner loops.
  • Maintain proper indentation.
  • Reset the inner loop variable in nested while loops.
  • Understand the execution order before writing pattern programs.
  • Practice dry runs to understand nested loop execution.

Quick Revision

  • A nested loop is a loop inside another loop.
  • The inner loop completes all its iterations for every iteration of the outer loop.
  • Nested loops are mainly used for patterns, tables, and matrices.
  • Use different loop variables such as i and j.
  • Proper indentation is essential for correct execution.

Important Python Programs on Loops

After learning the for loop, while loop, range(), break, continue, and nested loops, the next step is to apply these concepts by writing programs. This article contains important CBSE programs frequently asked in school examinations and practicals.


Program 1: Print Numbers from 1 to 10

for i in range(1,11):
    print(i)

Program 2: Print Even Numbers from 1 to 20

for i in range(2,21,2):
    print(i)

Program 3: Print Odd Numbers from 1 to 20

for i in range(1,20,2):
    print(i)

Program 4: Reverse Counting

for i in range(10,0,-1):
    print(i)

Program 5: Multiplication Table

n=int(input("Enter a number: "))
for i in range(1,11):
    print(n,"x",i,"=",n*i)

Program 6: Sum of First N Natural Numbers

n=int(input("Enter N: "))
sum=0
for i in range(1,n+1):
    sum=sum+i
print("Sum =",sum)

Program 7: Sum of Even Numbers

n=int(input("Enter N: "))
sum=0
for i in range(2,n+1,2):
    sum=sum+i
print("Sum =",sum)

Program 8: Sum of Odd Numbers

n=int(input("Enter N: "))
sum=0
for i in range(1,n+1,2):
    sum=sum+i
print("Sum =",sum)

Program 9: Sum of Squares

n=int(input("Enter N: "))
sum=0
for i in range(1,n+1):
    sum=sum+i*i
print("Sum =",sum)

Program 10: Sum of Cubes

n=int(input("Enter N: "))
sum=0
for i in range(1,n+1):
    sum=sum+i*i*i
print("Sum =",sum)

Program 11: Factorial Using for Loop

n=int(input("Enter a positive number: "))
fact=1
for i in range(1,n+1):
    fact=fact*i
print("Factorial =",fact)

Program 12: Factorial Using while Loop

n=int(input("Enter a positive number: "))
fact=1
i=1
while i<=n:
    fact=fact*i
    i=i+1
print("Factorial =",fact)

Program 13: Rectangle Star Pattern

for i in range(4):
    for j in range(5):
        print("*",end=" ")
    print()

Output

* * * * *
* * * * *
* * * * *
* * * * *

Program 14: Square Star Pattern

for i in range(5):
    for j in range(5):
        print("*",end=" ")
    print()

Program 15: Right Triangle Pattern

for i in range(1,6):
    for j in range(i):
        print("*",end=" ")
    print()

Output

*
* *
* * *
* * * *
* * * * *

Program 16: Inverted Triangle Pattern

for i in range(5,0,-1):
    for j in range(i):
        print("*",end=" ")
    print()

Program 17: Number Triangle

for i in range(1,6):
    for j in range(1,i+1):
        print(j,end=" ")
    print()

Program 18: Alphabet Pattern

for i in range(65,70):
    for j in range(65,i+1):
        print(chr(j),end=" ")
    print()

Program 19: Print All Characters of a String

name=input("Enter a string: ")
for ch in name:
    print(ch)

Program 20: Count from 1 to N Using while Loop

n=int(input("Enter N: "))
i=1
while i<=n:
    print(i)
    i=i+1

Programming Tips

  • Choose the appropriate loop based on the problem.
  • Use meaningful variable names.
  • Maintain proper indentation.
  • Test the program with different input values.
  • Dry-run the program before execution.

Common Errors

  • Forgetting to update the loop variable in a while loop.
  • Using incorrect range values.
  • Incorrect indentation.
  • Using = instead of == in conditions.
  • Creating an infinite loop unintentionally.

CBSE Practical Programs

  1. Print natural numbers.
  2. Print even and odd numbers.
  3. Generate multiplication tables.
  4. Calculate sums of different series.
  5. Find factorial of a number.
  6. Print star patterns.
  7. Print number patterns.
  8. Print alphabet patterns.
  9. Traverse strings.
  10. Write menu-driven loop programs.

Viva Questions

  1. Which loop is suitable when the number of iterations is known?
  2. Which loop is suitable when the number of iterations is unknown?
  3. What is the purpose of the range() function?
  4. Differentiate between break and continue.
  5. What is a nested loop?
  6. How is factorial calculated?
  7. What is the formula for the sum of the first N natural numbers?
  8. Why are nested loops used for pattern programs?
  9. Can factorial be calculated using a while loop?
  10. What precautions should be taken while writing loop programs?

Quick Revision

  • Use for when the number of iterations is known.
  • Use while when the number of iterations is not known.
  • Use break to terminate a loop.
  • Use continue to skip the current iteration.
  • Use nested loops for pattern-based programs.
  • Practice writing programs regularly to improve logical thinking.