Reputation: 27
I have little knowledge about the how the loops work.but the following program contain more then one loop and the if statement contain multiple OR operator.i am not sure how exactly the if statement works in this program, so some one please explain me.
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("Invalid Value");
} else {
//Rows
for (int i = 1; i <= number; i++) {
//Columns
for (int j = 1; j <= number; j++) {
if ((i == 1) || (i == number) || (j == 1) || (j == number) || (i == j) || (j == (number - i + 1))) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Upvotes: 0
Views: 45
Reputation: 407
if ((i == 1) - variable i is equal to 1?
|| OR
(i == number) variable i is equal to number?
||
(j == 1) variable j is equal to 1?
||
(j == number) j is equal to number?
||
(i == j) i is equal to j?
||
(j == (number - i + 1))) j is equal to number subtract i plus one?
If ANY of these statements are true, then the if statement is executed. The only time the else block is executed is when ALL of these statements are false. This is how the OR operator works.
Similarly the AND (&&) Operator is the opposite. ALL statements must be true in order for the if block to execute.
Hopefully that clears things up a little.
Upvotes: 1