Reputation: 45
Working on my 2nd triangle but it is not giving me the result needed using the while nested loop and I should have the following output.
Using for loop:
0
01
012
0123
01234
012345
Using while loops:
5
45
345
2345
12345
012345
Code:
print('Using for loop')
print()
M = 6 #constant
cnt = 1
for i in range(0,M):
for j in range(0,cnt):
if(j<M):
print(j,'',end='')
else:
print('',end='')
cnt+=1
print()
print()
print('Using While loop')
print()
cnt = 6
while(cnt != -1):
for j in range(0,cnt-1):
if(j<cnt+1):
print(j,'',end='')
else:
print(j)
cnt -=1
print()
print()
my current results are..
Using for loop
0
01
012
0123
01234
012345
Using while loop
012345
01234
0123
012
01
0
Upvotes: 0
Views: 1091
Reputation: 1936
Here is a while-loop solution without any for-loop:
print('Using While loop')
print()
cnt = 6
v = cnt
while(cnt != -1):
j = cnt
print(' ' * cnt, end='')
while(j < v):
print(j, end='')
j += 1
cnt -=1
print()
Upvotes: 0
Reputation: 1299
you have lot of syntax error use this
print('Using for loop')
print()
M = 6 #constant
cnt = 1
for i in range(0,M):
for j in range(0,cnt):
if(j<M):
print(j,'',end='')
cnt+=1
print()
print('\nUsing While loop\n')
cnt = 0
while(cnt != M):
for j in range(0,M-(cnt+1)):
print(' ','',end='')
for j in range(0,cnt+1):
print(M-(cnt+1-j),'',end='')
cnt +=1
print()
print()
Upvotes: 1
Reputation: 26039
Your logic is wrong. Also you have many syntax errors. Use this:
print('Using While loop')
print()
cnt = 6
v = cnt
while(cnt != -1):
print(' ' * cnt, end='')
for j in range(cnt, v):
if j < cnt+1:
print(j, end='')
else:
print(j, end='')
cnt -=1
print()
Output:
Using While loop
5
45
345
2345
12345
012345
Upvotes: 0