-3

I am trying to solve this practice problem.

a) Prompt the user to enter a value of n = positive integer

b) Allocate a 2d triangular list with n rows, first row has length 1, second row has length 2, etc, last row has length n

c) Write nested loops = outer loop and inner (nested) loop to iterate over all the elements in the 2d list. If the loop counter for the outer loop is i and loop counter for the inner (nested) loop is j, set the values of the array elements to i^2 + j^2

d) Print the list to the console so that the display looks like this

0

1 2

4 5 8

9 10 13 18

16 17 20 25 32

25 26 29 34 41 50

etc

This is what I have done so far.

n = int(input("Please enter a positive integer for n: "))
while n <= 0:
    n = int(input("Error: Please enter a positive integer for n: "))
for i in range(n):
    for j in range(i + 1):
        print(i**2 + j**2)

I haven't been able to figure out how to make the triangular shape. I know it's suppose to use lists but I haven't gotten it yet. If anyone has any tips, it would be very helpful! Thank you!

user14672805
  • 11
  • 1
  • 3
  • You are receiving downvotes because you didn't show your own attempt. This is usually perceived as disrespectful as you seem to expect others to write your code for you. Better show what you have done so far, no matter how little or misguided it may be =) – user2390182 Dec 07 '20 at 17:11
  • There is not [tag:python] in this question. Take the [tour] read about [ask] and see how to create a [mcve]. – Peter Wood Dec 07 '20 at 17:13

1 Answers1

0

Just follow the instructions...

# a) prompt the user
n = int(input("n: "))

# b) allocate a 2d triangular list
triangular = [ [0]*(i+1) for i in range(n) ]

# c) nested loops...
for i in range(n):
    for j in range(i+1):
        triangular[i][j] = i**2 + j**2

# d) print the list
for row in triangular: print(*row)

Sample run:

n: 5
0
1 2
4 5 8
9 10 13 18
16 17 20 25 32
Alain T.
  • 40,517
  • 4
  • 31
  • 51