Home > Net >  I need help converting this code from one for loop to two nested for loops
I need help converting this code from one for loop to two nested for loops

Time:11-15

This is an example of the wheat and chessboard problem. I need to write the code using one for loop and two nested for loops. I have written it using one for loop but am having trouble figuring out what I would do for my second for loop. Any help in the right direction would be appreciated!

Code with one for loop:

grains = 1
total = 0

n = int(input("How many squares are on one side of your chessboard?: "))
board = n ** 2

for i in range (0, board):
    total  = grains
    print ("row", int(i/n) 1, "column", (i%n) 1 , "has", grains, "grains of wheat.")
    grains = grains * 2

print ("There are", total, "grains of wheat.")

I think I need to do one for loop for the rows of the chessboard, and one for loop for the columns of the chessboard but don't know how to start writing it. I have also attached what the output needs to look like. Image of Output

CodePudding user response:

I am not particularly sure the reason for needing a nested loop other than you want to see how to get a comparable output, but you can analyze the following example. Which removes the need for the "board" variable.

grains = 1
total = 0

n = int(input("How many squares are on one side of your chessboard?: "))

for i in range (0, n):
    for j in range (0, n):
        total  = grains
        print ("row", i   1, "column", j   1, "has", grains, "grains of wheat.")
        grains = grains * 2

print ("There are", total, "grains of wheat.")

This results in the following output which should mimic your output image.

@Dev:~/Python_Programs/Grains$ python3 Grains.py 
How many squares are on one side of your chessboard?: 4
row 1 column 1 has 1 grains of wheat.
row 1 column 2 has 2 grains of wheat.
row 1 column 3 has 4 grains of wheat.
row 1 column 4 has 8 grains of wheat.
row 2 column 1 has 16 grains of wheat.
row 2 column 2 has 32 grains of wheat.
row 2 column 3 has 64 grains of wheat.
row 2 column 4 has 128 grains of wheat.
row 3 column 1 has 256 grains of wheat.
row 3 column 2 has 512 grains of wheat.
row 3 column 3 has 1024 grains of wheat.
row 3 column 4 has 2048 grains of wheat.
row 4 column 1 has 4096 grains of wheat.
row 4 column 2 has 8192 grains of wheat.
row 4 column 3 has 16384 grains of wheat.
row 4 column 4 has 32768 grains of wheat.
There are 65535 grains of wheat.

Give that a try to see if that meets the spirit of your project.

  • Related