Javascript nested for-loop pattern - javascript

I am trying to create an X or plus(+) pattern using javascript for-loop but fail to do it.
here is my code
function drawCross(){
var inputVal = document.getElementById("input").value;
if (inputVal % 2 === 0) { // checks if the user's entered value is even
document.getElementById("output").innerHTML = "";
for (var row = 0; row < inputVal; row++) {
for (var col = 0; col < inputVal; col++) {
if (row == col + 3 || row == parseInt(inputVal / 1))
document.getElementById("output").innerHTML += "O";
else
document.getElementById("output").innerHTML += "..";
}
document.getElementById("output").innerHTML += "<br/>";
}
}
}
this is the final result I am trying to achieve

A few issues:
Make sure your output element uses a monospace font. For instance, you could use a pre element for this. Then you don't have to double the points to get something that is still imperfect.
The input number should be odd, not even. Otherwise you don't have a center column/row.
The formula for the second diagonal is not like you have it (division by 1 does not make much sense). Use row == +inputVal - col - 1
Apart from that, also try to interact less with the DOM: only update it when you have the final HTML string.
Here is the code:
function drawCross(){
var inputVal = +document.getElementById("input").value;
var html = "";
if (inputVal % 2 === 1) { // checks if the user's entered value is odd
for (var row = 0; row < inputVal; row++) {
for (var col = 0; col < inputVal; col++) {
if (row == col || row == inputVal - col - 1)
html += "O";
else
html += ".";
}
html += "<br/>";
}
document.getElementById("output").innerHTML = html;
}
}
Enter odd number: <input id="input">
<button onclick="drawCross()">Go</button>
<pre id="output"></pre>

Related

Change the colour of cells with prime numbers in a dynamic table created with javascript

So far I have created the code to generate a table that has the number of cells that is defined by the user. In addition to this, the cells which have the prime numbers in it, must be coloured in a different colour. I have also included a function to find the prime numbers, but the approach I took to create the table, doesn't give me an option to implement the function onto the html body.
I would really appreciate any help.
Here's my code..
<html>
<head>
<style>
table{width: 70%;}
</style>
<script>
const numString= window.prompt("What is the loop maximum.? (between 1 and 500)")
let num=parseInt(numString);
if(num<0 || num>500)
{
window.alert("Warning! Must be between 1 and 500. Setting to default
100")
num=100
}
function isPrime(num)
{
for(var i=2; i< num; i++)
if(num % i ===0) return false;
return num>1;
}
</script>
</head>
<body>
<h1>Javascript Loops and Functions</h1><br>
<script>
document.write("<table border=1>");
let rows = num % 10 >= 0 && num % 10 <= 10 ? num / 10 + 1 : num / 10;
let count = 0;
for (row = 1; row <= rows; row++) {
document.write("<tr>");
for (let i = 1; i <= 10; i++) {
if (count >= num+1) break;
document.write("<td>" + count + "</td>");
count++;
}
document.write("</tr>");
}
document.write("</table>");
</script>
</body>
You can use a CSS class to give colors. For instance prime_true could be the class for prime numbers and prime_false for non-primes.
It is not so good practice to use document.write for such a purpose. So I would suggest to have an empty table element in your HTML, and then use loops to populate that table with rows and cells:
function isPrime(num) {
for(var i=2; i< num; i++)
if(num % i ===0) return false;
return num>1;
}
let table = document.querySelector("table");
for (let line = 1; line <= 500; line += 10) {
let row = table.insertRow();
for (let i = line; i < line + 10; i++) {
let td = row.insertCell();
td.textContent = i;
td.className = "prime_" + isPrime(i);
}
}
table { width: 70%; }
td { border: 1px solid; text-align: center }
.prime_true { background: orange }
.prime_false { background: lightgrey }
<h1>Javascript Loops and Functions</h1><br>
<table></table>
NB: this script should be in a script element that is put below the table element.
for (let i = 1; i <= 10; i++) {
if (count >= num+1) break;
if(isPrime(count)){
document.write("<td style='background-color:red'>" + count + "</td>");
} else {
document.write("<td>" + count + "</td>");
}
count++;
}

Something is not working in my code javascript to make a triangle

I made this code but it displays a line with spaces, I need to make a triangle with "*"
can someone help me telling me whats wrong?
function makeTriangle(){
let row, star;
let toPrint = "";
let rowCount =+prompt("enter number");
for (row = 1; row <= rowCount; row++) {
for (star = 1; star <= row; star++){
toPrint += "*";
}
toPrint +="\n\n";
}
document.getElementById("outputNumber").innerHTML = toPrint
}
What you are doing is using "\n\n" to add the line break. But to add line break, you have to use <br>. The reason is that, when the innerHTML is set to toPrint, the DOM shows stars in an indented form because of "\n\n". But when that HTML is rendered and displayed on the webpage, no line break is there. Therefore, you need to use HTML entity <br> to add line break.
function makeTriangle() {
let toPrint = "";
let rowCount = +prompt("enter number");
for (let row = 1; row <= rowCount; row++) {
for (let star = 1; star <= row; star++)
toPrint += "*";
toPrint += "<br>";
}
document.getElementById("outputNumber").innerHTML = toPrint
}
makeTriangle();
#outputNumber {
height: 100vh;
}
<div id="outputNumber"></div>

JavaScript Grid copy as String

I am having little problem on JavaScript. What I am doing is copying data from a grid and pasting into another. I was able to access the value from the cell, but problem comes as I try to format those value to string.
my code:
var colseperator = '~';
var rowseperator = ' ';
var clipStr = "";
if(selecttype = "area")
{
for (var i = startrow; i <= endrow; i++)
{
for (var j = startcol; j <= endcol; j++)
{
var cellValue = objGrid.getCellValue(i,j);
if(this.gfn_isNull(cellValue))
{
cellValue = "Null";
}
clipStr = clipStr + cellValue;
if(j != endcol)
{
clipStr = clipStr + colseperator;
}
}
if(i != endrow)
{
clipStr = clipStr + rowseperator;
}
}
}
From code above, my intention is copy the data into string format and separate each data with separator(in my case '~' for columns and 'indent' for rows). However, when I select one column(multi rows) and copy it, it would add column separators to all the rows.
I was thinking that if(j != endcol){clipStr = clipStr + colseperator;} would stop it from adding unnecessary separator. Am I doing something wrong here? And any tips on iterating the selected grid cells or formatting string?
example:
When I select those three lines,
row
data
1
a
2
b
3
c
Output:
a~ b~ c~
My expected output:
a b c
You could add a variable for a cols and add the separator if not iteratng the first item.
var colseperator = '~',
rowseperator = ' ',
clipStr = "";
if (selecttype = "area") {
for (var i = startrow; i <= endrow; i++) {
var cols = "";
for (var j = startcol; j <= endcol; j++) {
var cellValue = objGrid.getCellValue(i, j);
if (this.gfn_isNull(cellValue)) cellValue = "Null";
if (j !== startcol) cols += colseperator;
cols += cellValue;
}
if (j !== startcol) clipStr += rowseperator;
clipStr += cols;
}
}

How to append multiplication result of 2 vars in table cells?

I'm prompting the user to enter a number for row and another for column, then construct a table using the given numbers and numbering each cell accordingly.
However, I want my final result to be displayed as a multiplication table, like the image below:
multiplication table image
And here's what my code looks like so far:
var table = document.getElementById("table");
var temp = "<table border = 1 border-collapse = collapse>";
for (var i = 0; i < row; i++){
temp += "<tr>";
if (i == 0){
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (j+1) + "</td>";
}
} else{
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (i+1) + "</td>";
}
}
temp += "</tr>";
}
temp += "</table>";
table.innerHTML=temp;
That is nearly right already. What you are looking for is to put (i+1)*(j+1) in the second for statement.
I'm not sure how you get your user input. Prompt is not usually a great way to get input but because you said that's what you used the example below uses prompt. The problem with it is that it blocks everything else: not only your own webpage, but the entire browser. If you have not done so already, you might consider getting your user-inputted numbers from an HTML form.
You might also want input checking code. I've included it below in a full HTML/JS solution. It gives the user 3 chances to enter a number for both the row and the column. If the user fails to do so, it outputs an error message.
<html>
<head>
</head>
<body>
<div id='table'></div>
<script>
var table = document.getElementById('table');
var attemptCounter = 0;
var maxAttempts = 2;
var temp='<table border = 1 border-collapse = collapse>';
var row;
var column;
while ((typeof row !=='number' || attemptCounter <= maxAttempts) && isNaN(row) ){
var row = parseInt(prompt("Please enter the number of ROWS for your table:"),10);
if(typeof row ==='number' && !isNaN(row)){break;};
attemptCounter++;
}
if(attemptCounter >= maxAttempts+1){
table.innerHTML = 'Error: expected NUMBER for number of rows';
}
if(attemptCounter < maxAttempts+1){
attemptCounter = 0;
while ((typeof column !=='number' || attemptCounter <= maxAttempts) && isNaN(column) ){
var column = parseInt(prompt("Please enter the number of COLUMNS for your table:"),10);
if(typeof column ==='number' && !isNaN(column)){break;};
attemptCounter++;
}
if(attemptCounter < maxAttempts+1){
for (var i = 0; i < row; i++){
temp += "<tr>";
if (i == 0){
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (j+1) + "</td>";
}
} else {
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (i+1)*(j+1) + "</td>";
}
}
temp += "</tr>";
}
temp += "</table>";
table.innerHTML=temp;
} else {
table.innerHTML = 'Error: expected NUMBER for number of columns';
}
}
</script>
</body>
</html>
Your code nearly works. If you change your (i+1) and (j+1) to (i * j) you'll see that the table created works, except for the first row and first column (as multiplying by 0 will always give 0).
However to deal with the multiplication with 0 in the first column and row there needs to be some conditional that checks if one of the values (either i or j are 0) and then changes the value to 1.
I've only changed what happens in your for loop.
for (var i = 0; i < row; i++){
temp += "<tr>";
for (var j = 0; j < column; j++){
// Here I have split your temp string.
temp += "<td height = 20 width = 40>";
if (i == 0 && j ==0){ // if both i and j are 0 then add a 0 to temp.
temp += 0;
} else {
// Multiply them together changing 0 to 1 (solving the 0's problem)
temp += (i == 0 ? 1 : i) * (j == 0 ? 1 : j);
}
temp += "</td>";
}
temp += "</tr>";
}
temp += "</table>";
table.innerHTML=temp;
i==0?1:i is a ternary operator which is just like a little if statement. It checks if i is 0 and if it evaluates to true it returns 1, otherwise it returns the value of i. Read more about it here
Putting it all together,
temp += (i==0?1:i) * (j==0?1:j) multiplies the values in the table together and also prevents multiplication with 0 in the headings.
Build HTML as string is not bad but it is better to work with DOM model. Here is an example.
<!DOCTYPE html>
<html>
<head>
<title>Build Table</title>
<meta charset="utf-8" />
<style type="text/css">
.tbl{border:solid 1px #ccc}
.tbl tr:first-child td,
.tbl td:first-child{background:#ccc;padding:4px}
</style>
<script type="text/javascript">
'use strict';
function buildTable() {
//get numbers from micro-form
var rows = document.getElementById('rows').value;
var cols = document.getElementById('cols').value;
//create table
var tbl = document.createElement('table');
tbl.className = 'tbl';//it is better then inline style
//note that HTML table has its own DOM model
var tr = tbl.insertRow(-1);//insert new row
//first row is special
tr.insertCell(-1).innerHTML = 'X';
//so treat it accordingly
for (var i = 1; i < cols; i++) {
tr.insertCell(-1).innerHTML = i;//insert new cell and set value inside
}
//remaining rows
for (i = 1; i < rows; i++) {
tr = tbl.insertRow(-1);
//first column is special
tr.insertCell(-1).innerHTML = i;
for (var j = 1; j < cols; j++) {
tr.insertCell(-1).innerHTML = i * j;
}
}
//well done. Place our table in a container
document.getElementById('table').appendChild(tbl);
}
</script>
</head>
<body>
<div>
Rows: <input type="number" id="rows" min="2" max="10" value="10" />
Columns: <input type="number" id="cols" min="2" max="10" value="10" />
<button onclick="buildTable()">Build Table</button>
</div>
<div id="table"></div>
</body>
</html>

How can I get this loop's information in a table (Javascript)

I'm trying to get the loop that is in the code after this text to have the information outputted into a table. To explain this further, the function function doEvens() creates a loop that takes uses the number a person enters into the input text box Type in your Number: <input type="number" id="num">, and displays all even numbers between that number and 2 within a paragraph: <p id="space"></p>, when the numbers are displayed within the paragraph they have a semicolon and a space separating them, instead of that I would like the numbers to be within a table, I have tried using createElementById and with no luck, I have tried putting a table between certain areas of the code, with no luck I still have not been able to fix this, I have many other projects I am working on and I am not very good at coding.
<!DOCTYPE html>
<html>
<head>
<script>
function doEvens() {
var number = document.getElementById('num').value;
if(number > 1) {
if(number % 2 == 0) {
while(number > 2) {
document.getElementById("space").innerHTML += (+number - 2) + "; ";
number = +number - 2;
}
} else {
number--;
alert(number);
while(number > 1) {
document.getElementById("space").innerHTML += (+number - 2) + "; ";
number = +number - 2;
}
}
}
}
</script>
</head>
<body>
Type in your Number: <input type="number" id="num">
<button onclick="doEvens();" href="javascript;">Submit</button>
<p id="space"></p>
</p>
</body>
</html>
I have implemented the solution with table. Here it is:
function doEvens() {
var number = document.getElementById('num').value,
table = document.getElementById('evensTable'),
cellsInRow = 20,
evens = [],
tableContent = '',
row = '',
i = 3,
startAt,
numberOfRows;
table.innerHTML = '';
while (i++ < number - 1) {
i % 2 === 0 && evens.push(i);
}
numberOfRows = evens.length / 20;
for (var r = 0; r < numberOfRows; r++) {
row = '<tr>';
startAt = r * cellsInRow;
for (var c = startAt; c < startAt + cellsInRow; c++) {
if (!evens[c]) break;
row += '<td>' + evens[c] + '</td>';
}
row += '</tr>';
tableContent += row;
}
table.innerHTML = tableContent;
}
<body>
Type in your Number:
<input type="number" id="num">
<button onclick="doEvens();" href="javascript;">Submit</button>
<table id="evensTable">
</table>
</body>
This table contains one row, but you can also create more rows in code (say after every 10 numbers print)
If something is not clear for you, please ask me.
UPDATE
I have updated the solution as per your needs.

Categories