Python Program to print Zigzag Pattern
In this tutorial, we will learn to print Zigzag Pattern in Python.
Basically in a Zigzag pattern, we need to print numbers in sequential order in odd rows and reverse order in even rows and the number of elements in each row will be equal to their row number.
Various steps involved are:
- Given a number (n), initialize a loop from 1 to n+1 i.e. n times.
- Take 2 variables, start1 and start2 and initialize them with 0 where start1 points to the starting number of odd rows and start2 points to the starting number of even rows.
- For odd rows, start1 = start2+i and increment start1 after each iteration.
- For even rows start2=start1+i-1 and decrement start2 after each iteration.
- Now create an inner loop till i and print the numbers.
Practical Demonstration: Python code to print a zigzag pattern with numbers
n=6 start1=0 start2=0 for i in range(1,n+1): if i%2!=0: start1=start2+i for j in range(i): if j==0: print(start1,end=' ') else: print('* ',start1,end=' ') start1+=1 else: start2=start1+i-1 for j in range(i): if j==0: print(start2,end=' ') else: print('* ',start2,end=' ') start2-=1 print()
Output : 1 3 * 2 4 * 5 * 6 10 * 9 * 8 * 7 11 * 12 * 13 * 14 * 15 21 * 20 * 19 * 18 * 17 * 16
Recommended Posts:
Leave a Reply