Reputation: 48
I was stuck with the problem I was facing.
the code that i have tried :
function printImage(oddnumbers) {
for (var i = 0; i < oddnumbers; i++) {
var tmp = ''
for (var j = 0; j < oddnumbers; j++) {
if (i % 2 === 0) {
tmp += 'x';
} else {
tmp += '=';
}
}
console.log(tmp);
}
}
printImage(5)
this is the result
xxxxx
=====
xxxxx
=====
xxxxx
I have a problem like this:
Make a function to print the image as below, which has a parameter as the length or width of the image. The parameter must be odd numbers. Note: Must use looping, don't hardcode / write directly
when i run printImage(5)
x===x
=x=x=
==x==
=x=x=
x===x
when i run printImage(7)
x=====x
=x===x=
==x=x==
===x===
==x=x==
=x===x=
x=====x
please helpme to solve this problem
Upvotes: 1
Views: 1227
Reputation: 370759
You need to print x
s along the diagonals, which can be done by checking when making a row: if the row index (the j
) is the same as the column index (the i
), print x
(since you're on the top-left to bottom-right diagonal), and if the row index is equal to length - 1 - i
, you're on the other diagonal. Otherwise, print =
:
function printImage(length) {
for (var i = 0; i < length; i++) {
// Construct a row
var tmp = ''
for (var j = 0; j < length; j++) {
tmp += (j === i || j === (length - 1 - i))
? 'x'
: '=';
}
console.log(tmp);
}
}
printImage(7)
Upvotes: 1