Web  Hopeful
Web Hopeful

Reputation: 761

Strange issue with values a while loop?

I am working on a program that prints out steps and running into a strange problem with a while loop. For some reason the loop starts at 1 instead of 0 and I can't pinpoint why it is exactly.

Current Output:

Array Rows: 5
Array Columns: 5
_ _ _ _ _ 
X _ _ _ _ 
X X _ _ _ 
X X X _ _ 
X X X X _ 

Desired Output:

Array Rows: 5
Array Columns: 5
X _ _ _ _ 
X X _ _ _ 
X X X _ _ 
X X X X _ 
X X X X X

Code For Function:

if(rows == columns):
        x = 0
        while(x < rows):
            y = 0
            while(y < x):
                array[x][y] = "X"
                y += 1
            x += 1 

Note: The rows and columns are user inputs from the main program to specify how large the 2D list should be.

Here is the output with a debugging print showing the issue:

Array Rows: 5
Array Columns: 5
1
2
2
3
3
3
4
4
4
4
_ _ _ _ _ 
X _ _ _ _ 
X X _ _ _ 
X X X _ _ 
X X X X _ 

Note: The change in this output is a print statement of "x" in the 2nd nested while loop.

Any help would be greatly appreciated as I've spent a ton of time trying to figure out what is wrong without any luck :/

Upvotes: 0

Views: 98

Answers (2)

Kevin Ji
Kevin Ji

Reputation: 10499

You probably want to test whether y <= x, as on the diagonal, your row number will be equal to your column number.

if rows == columns:
    x = 0
    while x < rows:
        y = 0
        while y <= x:
            array[x][y] = "X"
            y += 1
        x += 1

Just a hint: you could use a for loop to make this a bit simpler:

if rows == columns:
    for x in range(0, rows):
        for y in range(0, x + 1):
            array[x][y] = "X"

Upvotes: 1

Joe Z
Joe Z

Reputation: 17936

There will be 0 X's in row 0, 1 X in row 1, etc. with your current code. That's because on row 0, the inner while loop iterates 0 times, because the initial test x < y fails before the loop starts. 0 is not less than 0.

Perhaps you want y <= x in your inner while loop?

Upvotes: 1

Related Questions