最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript print square using for loop and conditional statement only - Stack Overflow

programmeradmin5浏览0评论

Just started my uni course, struggling a little with javascript. I have been asked to display a square using any character, however, the solution must bine for loops and if statements.

This is what I have so far and I feel pretty close but I just can't get the second line to display. I know this can be done via two for loops, (one for iteration of the variable and another for spaces). But this is not how I have been asked to solve this problem.

Here is my code:

var size = 3;
let i;


for(i = 0; i < size; i++) {
print ("*");
if (size === i){ 
println (""); 
}
}

For context, this is all taking place int he professors homemade learning environment.

Just started my uni course, struggling a little with javascript. I have been asked to display a square using any character, however, the solution must bine for loops and if statements.

This is what I have so far and I feel pretty close but I just can't get the second line to display. I know this can be done via two for loops, (one for iteration of the variable and another for spaces). But this is not how I have been asked to solve this problem.

Here is my code:

var size = 3;
let i;


for(i = 0; i < size; i++) {
print ("*");
if (size === i){ 
println (""); 
}
}

For context, this is all taking place int he professors homemade learning environment.

Share Improve this question asked Oct 13, 2017 at 10:28 Simon DeanSimon Dean 2371 gold badge4 silver badges16 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

You could use nested for loops and take a line break after each filled line.

function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }

var size = 5,
    i, j;

for (i = 0; i < size; i++) {
    for (j = 0; j < size; j++) {
        print("*");
    }
    println("");
}
<pre id="out"></pre>

Single loop with a check if i is unequal to zero and if the remainder is zero, then add a line break.

Using:

  • === identity/strict equality operator checks the type and the value, for example if both are numbers and if the value is the same,

  • !== non-identity/strict inequality operator it is like above, but it checks the oposite of it,

  • % remainder operator, which returns a rest of a number which division returns an integer number.

  • && logical AND operator, which check both sides and returns the last value if both a truthy (like any array, object, number not zero, a not empty string, true), or the first, if it is falsy (like undefined, null, 0, '' (empty string), false, the oposite of truthy).

function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }

var size = 5,
    i;

for (i = 0; i < size * size; i++) {
    if (i !== 0 && i % size === 0) {
        println("");
    }
    print("*");
}
<pre id="out"></pre>

Well the for loop is only iterating 3 times, printing the first line. If you want a square you'll have to print 9 stars total, right? So i'm assuming, is this is the approach you'd go for, you would need to iterate not until size, but until size * size.

I'm using console.log to 'print' the square:

    var dimension = 10;
    var edge = '*';
    var inside = ' ';
    var printLine;

    for (var i = 1; i <= dimension; i++) {
        if (i === 1 || i === dimension) {
            printline = Array(dimension + 1).join(edge);
        } else {
            printline = edge + Array(dimension - 1).join(inside) + edge;
        }
        console.log(printline);
    }

Note that in the following example, an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements:

Array(11).join('a'); // create string with 10 as "aaaaaaaaaa"

You wanna make a square of * where the size is the number of * on its sides?

Let's split a task into 3 parts:

  • where you print top side like *****
  • where you print middle (left and right sides) like * *
  • where you print bottom (same as top)

Now let's code that, I kept the code as simple as possible, this can be done in fewer lines but I think this will be easier to understand for beginners:

var size = 5;
var i = 0;

// top
for (i = 0; i < size; i++)
    console.log("*");

//middle
for (var j = 0; j < size - 2; j++){
  console.log("\n"); // go to next row
  // middle (2 on sides with size-2 in between)
  console.log("*");
  for (i = 0; i < size-2; i++)
    console.log(" ");
  console.log("*\n"); // goes to new row as well
}

// same as top
for (i = 0; i < size; i++)
    console.log("*");

Full square is even simpler:

var size = 5;
var i = 0;

for (var i = 0; i < size; i++){ // iterates rows
  for (var j = 0; j < size; j++) // iterates * in row
      console.log("*");
  console.log("\n") // moves to new row
}

In order to print a row, you print same sign X times. Well, to print X rows we can use just that 1 more time (only this time we are iterating over a different variable (j is * in a row, i is a number of rows).

After a row is made we go to go to next row with \n.

As for

it must contain if statement

Put this at the end:

if (youCanHandleTheTruth) console.log("It's a terrible practice to tell students their solution MUST CONTAIN CODEWORDS. If you need them to showcase something, write appropriate task that will require them to do so.");
发布评论

评论列表(0)

  1. 暂无评论