Remmargrop
Remmargrop

Reputation: 15

Nested For Loops Giving Incorrect Output

I'm trying to get the following output from my code:

x  o  o  o  o  
x  x  o  o  o  
x  x  x  o  o  
x  x  x  x  o  
x  x  x  x  x

Here is my code:

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        if (i == j) {
            System.out.print(" x ");
        } else {
            System.out.print(" o ");
        }
    }
    System.out.println();
}

But I'm not able to get the correct output. I'm getting the following output using this code:

 x  o  o  o  o 
 o  x  o  o  o 
 o  o  x  o  o 
 o  o  o  x  o 
 o  o  o  o  x 

Upvotes: 0

Views: 72

Answers (2)

CFSO6459
CFSO6459

Reputation: 95

Just change if(i == j) to if(j <= i) and everything will work!

Long explanation:

Think about the logic

  • i is the outer loop, take charge of each row
  • j is the inner loop, print each character(x and o) with-in the line
  • So how much x should be print (i.e. value of j), depending on the line number (i.e. i)
  • Printing x from the first position (j == 1), to the i position (j == i), that is, j from 1 to i, which write in Java is j <= i

Upvotes: 2

ninja.coder
ninja.coder

Reputation: 9658

With the condition i == j you will only get the x in the diagonal elements. If you want the desired output then you'll have to modify the condition to i >= j instead.

Here is the corrected code snippet:

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        if (i >= j) {
            System.out.print(" x ");
        } else {
            System.out.print(" o ");
        }
    }
    System.out.println();
}

Output:

 x  o  o  o  o 
 x  x  o  o  o 
 x  x  x  o  o 
 x  x  x  x  o 
 x  x  x  x  x 

Upvotes: 0

Related Questions