You are on page 1of 2

Repetition_NestedForLoops

Ibrahim Abou-Faycal

#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Repetition - Nested for Loops

Reading: [Guttag, Chapter 3] Material in these slides is based on


• Slides of EECE-230C & EECE-230 MSFEA, AUB
• [Guttag, Chapter 3]

0.1 Nested loops


Example:
• Two nested loops: outer loop whose body contains another loop
• Simple example: Given user input n, print the pattern:
1
12
123

123…n
[ ]: n = int(input("Enter n:"))
for i in range(1,n+1): # i is the line number
# Print the numbers 1...i followed by a new line:
# First print the numbers 1...i
for j in range(1,i+1):
print(j, end=' ')
# then print new line (default: end='\n')
print('')

Alternative implementation:

1
[ ]: n = int(input("Enter n:"))
for i in range(1,n+1):
for j in range(1,i):
print(j,end=' ')
print(i) # default end='\n'

Variation: Print in reverse


[ ]: n = int(input("Enter n:"))
for i in range(n,0,-1):
for j in range(1,i):
print(j,end=' ')
print(i) # default end='\n'

You might also like