This is my javascript code for the Y pattern but in the bottom part, it is not in the center what’s wrong with my code? will accept odd numbers
const char = "Y";
const size = 5; //all odd numbers
let output = ""
if (char === 'Y') {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === 0 && i >= size / 2))
{
output += 'O';
} else {
output += ' ';
}
}
output += '\n';
}
}
console.log(output);
I expect to have this output:
O O
O O
O
O
O
>Solution :
Changing j === 0 to j === 2 will solve this problem. For work universally, just use j === (size - 1) / 2
const char = "Y";
const size = 5;
let output = ""
if (char === 'Y') {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === (size - 1) / 2 && i >= size / 2))
{
output += 'O';
} else {
output += ' ';
}
}
output += '\n';
}
}
console.log(output);