📘 Nested while Loop in Python
🎯 What is Nested while Loop?
A nested while loop means a while loop inside another while loop.
It is used when:
- patterns
- tables
- grids
- matrix operations
- repeated iterations inside iterations
📌 Definition
A nested while loop is a loop structure where one while loop is placed inside another while loop.
🧠 Syntax
while condition1:
while condition2:
# code
🔁 Key Concept
- Outer loop = rows
- Inner loop = columns
- Inner loop completes fully for each outer loop
📘 Pattern Programs (Code + Output)
1. Square Pattern
CODE:
i = 1
while i <= 5:
j = 1
while j <= 5:
print("*", end=" ")
j += 1
print()
i += 1
OUTPUT: * * * * * * * * * * * * * * * * * * * * * * * * *
2. Right Triangle
CODE:
i = 1
while i <= 5:
j = 1
while j <= i:
print("*", end=" ")
j += 1
print()
i += 1
OUTPUT: * * * * * * * * * * * * * * *
3. Reverse Triangle
CODE:
i = 5
while i >= 1:
j = 1
while j <= i:
print("*", end=" ")
j += 1
print()
i -= 1
OUTPUT: * * * * * * * * * * * * * * *
4. Number Triangle
CODE:
i = 1
while i <= 5:
j = 1
while j <= i:
print(j, end=" ")
j += 1
print()
i += 1
OUTPUT: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
5. Same Number Pattern
CODE:
i = 1
while i <= 5:
j = 1
while j <= i:
print(i, end=" ")
j += 1
print()
i += 1
OUTPUT: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
6. Floyd’s Triangle
CODE:
num = 1
i = 1
while i <= 5:
j = 1
while j <= i:
print(num, end=" ")
num += 1
j += 1
print()
i += 1
OUTPUT: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
7. Pyramid Pattern (IMPORTANT)
CODE:
i = 1
while i <= 5:
print(" "*(5-i), end="")
j = 1
while j <= i:
print("*", end=" ")
j += 1
print()
i += 1
OUTPUT:
*
* *
* * *
* * * *
* * * * *
8. Number Pyramid
CODE:
i = 1
while i <= 5:
print(" "*(5-i), end="")
j = 1
while j <= i:
print(j, end=" ")
j += 1
print()
i += 1
OUTPUT:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
9. Reverse Number Pattern
CODE:
i = 5
while i >= 1:
j = 1
while j <= i:
print(j, end=" ")
j += 1
print()
i -= 1
OUTPUT: 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1
10. Alphabet Pattern
CODE:
i = 0
while i < 5:
j = 0
while j <= i:
print(chr(65+j), end=" ")
j += 1
print()
i += 1
OUTPUT: A A B A B C A B C D A B C D E
No comments:
Post a Comment