Writing a times table? - javascript

I know this may seem like a simple question but I'm stumped. I'm supposed to create a times table using increments of 12. While I can use any method, I'm attempting to use a for loop. The formula works just fine, it multiplies 'number' by 12, but I need to put, for instance, 12 * 1 = 12, rather than 12 * = 12 which is what I have now. Is there anything that I can do to improve upon this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var number = 0;
i = 0
for (number; number <=12; number++) {
document.write("12 * " + number * 12 + "</br>");
i++;
}
</script>
</body>
</html>

I think this may be what you're trying to accomplish, which involves ensuring you output the value of your iterating variable (number in this case).
var number = 0;
for (number; number <=12; number++) {
document.write("12 * " + number + " = " + number * 12 + "</br>");
}

Related

show random number < 0.8 not working properly

Hi I'm kinda new on JS so I tried to do this, I made this to test the random function and I want to show only random numbers below 0.8, but sometimes it shows above 0.8 also more than one time in a row, how do I fix it ?
This is my first post ever here, so sorry if I did something wrong.
Thanks. :)
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
if (rn() < 0.8) {
document.write(rn() + "<br>")
}
if (rn() > 0.8) {
x = 100
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>exp</title>
</head>
<body id="bd">
<h1 id="11"></h1>
</body>
<script src="exp.js"></script>
</html>
Your code makes two random number calls, each of which may have a different value. The fix is to use else to ensure only one branch fires:
let n = Math.random();
if (n < 0.8) {
document.write(n + "<br>")
}
else {
x = 100
}
Just because you've wrapped Math.random() in a function doesn't mean it fires only once. Each and every call to rn() will return a new value. The local variable a is initialized anew with each function call. It does not persist between calls.
In your original code around 16% of the time (80% x 20%) you'd fluke out and trigger both branches.
Assign the return value to a variable in order to hold the same value over different conditions.
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
const randomNumber = rn();
if (randomNumber < 0.8) {
document.write(randomNumber + "<br>")
}
if (randomNumber > 0.8) {
x = 100
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
The problem is that you're calling rn() multiple, and it returns different numbers each time. The result you test in if is not the same one that you display with document.write(), or the one that you test in the second if.
You need to save the number to a variable so you can test and display the same number.
Also, use else when you want to do something when the previous test failed.
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
var num = rn();
if (num < 0.8) {
document.getElementById("bd").innerHTML += (num + "<br>")
} else {
break;
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>exp</title>
</head>
<body id="bd">
<h1 id="11"></h1>
</body>
<script src="exp.js"></script>
</html>

How to generate set of arrays when clicking button, without disappearing the first one?

Im trying to learn js. Im starting playing with array by generating 6 combination numbers. This is working but i dont know how to output another combinations when I click the button. Any comment is appreciated. THanks
function getRandomNumber() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var arr = [];
while(arr.length < 8){
var myrandomnumber = Math.floor(Math.random(x) * y + 1);
if(arr.indexOf(myrandomnumber) === -1) arr.push(myrandomnumber);
}
if (x==""){
alert("Please enter a number");
}
else if (y==""){
alert("Please enter a number");
}
else{
document.getElementById("ok").innerHTML = arr;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RANDOM NUMBER JS</title>
<meta name="" content="">
<link rel="stylesheet" href="css/css/bootstrap.css">
<link rel="stylesheet" href="css/cssextra/csse1.css">
<script src="customscript.js"></script>
</head>
<body class="bg-light">
<br>
<p id="demo">Random Number</p>
<br><br>
<input type="number" id="num1" name="one"/ >
<input type="number" id="num2" name="two"/ >
<button onclick="getRandomNumber();">Generate random number</button >
<p id="ok"></p><br>
<p id="okok"></p>
</body>
</html>
Accumulate results
A easy yet crude solution would be appending the current text with <br> for line breaks:
const p = document.getElementById("ok");
p.innerHTML = p.innerHTML + (p.innerHTML === "" ? "" : "<br>") + arr.join(", ");
But this approach will notoriously perform badly as the text grows larger.
If you change the p elements into:
<div id="ok" class="text-container">
And replace the script's document.getElementById("ok").innerHTML = arr; into:
const p = document.createElement("p");
p.textContent = arr.join(", ");
document.getElementById("ok").appendChild(p);
And add css:
.text-container {
margin-top: 1em;
}
.text-container > p {
margin: 0;
}
Then you should have something working.
Also there are some things to address:
Math.random()
The function Math.random() does not take arguments, so your variable x does not have any effect.
If the intention is to x and y as a minimum and maximum value, try this from Math.random() - JavaScript | MDN:
function getRandomInt(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
The min is inclusive and the max is exclusive. If x = 0 and y = 10, and you want the range to be [0-10], you can do getRandomInt(x, y + 1).
Make sure min is not greater than max.
Prevent infinite loop
Your loop will get stuck if the amount of possible unique integers is smaller than the number of array elements required for it to end.
More user input semantics
Variables x and y are tested before writing out the numbers, but after they have already been used to generate the numbers. In other words, the number creation process should be moved into the else block.
innerHTML expects a string and you are setting the array.
use document.getElementById("ok").innerHTML = arr.join(' ');
this will concatenate each element in the array with a space as glue

Adding sum of an array but getting NAN

I'm trying to create a working time clock that allows me to input the number of hours I study everyday and get the total. Am I using parseInt wrong?
<html>
<head>
<title>Time clock</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="header">Time clock</h1>
<p id="greeting"></p>
<input type="text" id="inp"/>
<button onclick="sumit()">Click</button>
<p id="hours"></p>
<script>
greeting.innerHTML = 'How many hours have you studied?'
function sumit(){
let text = parseInt(document.getElementById("inp").value);
let hours = (document.getElementById("hours"));
let total = 0
for (i = 0; i < 10; i++){
total += parseInt(text[i]);
hours.innerHTML = `You have studied a total of ${text + total} hours.`
}
console.log(total)
console.log(text)
}
</script>
</body>
</html>
The text variable is already defined and assigned the value of parseInt. So your total += parseInt(text[i]) is trying to index a number type (e.g. total += 123[0]) which isn't possible. Instead, you can just do total += text, or you can remove the parseInt call when you declare text and then do total += parseInt(text).
With minimal changes, this should work:
function sumit() {
let text = parseInt(document.getElementById("inp").value) || 0;
let hours = document.getElementById("hours");
let total = 0;
total += text;
hours.innerHTML = `You have studied a total of ${total} hours.`;
}
Explanation
parseInt can return NaN, so we use the || operator to let it default to 0
You don't need to loop over anything to sum the number
Even if you were looping over anything, you don't use reference indexes on numbers like you tried to do with text[i]
You don't need to add total to text multiple times

finding Middle element of an array in javascript

I need to write a program that finds the middle of an array and returns the value stored there unless the array is even then it should return the average of the two middle most numbers. Here is the code i have so far. i'm stuck on how i would find the middle two numbers in an even array and return the average. I'm a super beginner in java script so all help is appreciated. Thanks!
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Add Ends</title>
<script language="javascript" type="text/javascript">
/*
Write a function named getMiddle that returns the value of the middle element in an array. If the array has an even number of elements, then this function must return the average of the two middle elements.
*/
var testNumbers = [0, 1 ,2, 3, 4, 5, 6, 7, 8, 9]
function isEven()
{
var mid = (testNumbers[0] + (testNumbers.length)) / 2;
}
function getMiddle(list)
{
var mid = (testNumbers[0] + (testNumbers.length)) / 2;
if (mid % 2 == 0)
{
var evenMid = isEven();
document.getElementById("outputDiv1").innerHTML = evenMid;
}
else
{
document.getElementById("outputDiv1").innerHTML = mid;
}
}
</script>
</head>
<body>
<button type="button" onclick="binarySearch()">Find the Middle</button>
<br>
<div id="outputDiv1"></div>
</body>
</html>
This should get you somewhere (from this SO answer):
if (nums.length %2 == 0) {
// even-length array (two middle elements)
var avg = (nums[(nums.length/2) - 1] + nums[nums.length/2]) /2;
}
Try the following:
/*
Write a function named getMiddle that returns the value of the middle element in an array. If the array has an even number of elements, then this function must return the average of the two middle elements.
*/
var testNumbers = [0, 1 ,2, 3, 4, 5, 6, 7, 8, 9]
function output(){
var mid = getMiddle(JSON.parse(document.getElementById("lst").value));
outputDiv1.innerHTML = mid;
}
function getMiddle(list)
{
if(list.length % 2 == 1){
return list[(list.length-1)/2];
}else{
return (list[(list.length/2)]+list[(list.length/2 -1)])/2
}
}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Add Ends</title>
</head>
<body>
<input id="lst">
<button type="button" onclick="output()">Find the Middle</button>
<br>
<div id="outputDiv1"></div>
</body>
</html>
var idx = (testNumbers.length-1) / 2;
document.getElementById('outputDiv1').textContent =
( testNumbers[Math.floor(idx)] + testNumbers[Math.ceil(idx)] )/2;

Print 5 times table from 1 o 12

I seem to have everything I need for the what I am trying to do. However, I can't seem to get it display how I want it to display.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>5 Times Table</title>
<script type="text/javascript">
/* Program to print the five times table from 1 to 12 in this format:
5 x 1 = 5
5 x 2 = 10
5 x ...
Input: There will be no user input, program will use a loop to create the 5 times table.
Process: Define all the 5 times table between 1 and 12.
Output: The 5 times table will be displayed.
*/
function fiveTimesTable() {
var result = 0;
for (i=1; i<=12; i++){
result = "5 * " + i + result + i*5 + "<br>";
var display =result;
}
document.getElementById("outputDiv").innerHTML = display;
}
</script>
</head>
<body>
<h1>Five Times Table From 1 - 12.</h1>
<h2>Press the button to display the table.</h2>
<button type="button" onclick="fiveTimesTable()">Times Table</button>
<div id="outputDiv"></div>
</body>
</html>
`
Your code was close, but it'll be easier to understand if you break it up into its parts.
function fiveTimesTable() {
var display = ""; // The table output HTML
for (i = 1; i <= 12; i++) {
var multiplier = 5;
var result = i*5;
display += multiplier+" * "+i+" = "+result+"<br>"; //Add each line to our output HTML
}
document.getElementById("outputDiv").innerHTML = display;
}
Check it out in this codepen.
Some challenges going forward, if you're interested.
Make your function able to display the table for any multiplier using parameters.
Put your table into an actual HTML table element.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Tabla del 5</title>
<script>`enter code here`
/* Program to print the five times table from 1 to 12
Input: The program will use a loop to create the 5 times table.
Process: Write a defining table and a program to display the five times tables
Output: display the five times table from 1 to 12 in this format*/
function FiveTimesTable() {
var display = "";
for (i = 1; i <= 12; i++) {
var multiplier = 5;
var result = 5*i;
display += multiplier+" * "+i+" = "+result+"<br>"+"<br>";
}
document.getElementById("outputDiv").innerHTML = display;
}
</script>
</head>
<body>
<h2>Five Times Table</h2>
<h3>Press the button to display the 5 times table</h3>
<button type="button" onclick="FiveTimesTable()">Times Table</button>
<div id="outputDiv"></div>
</body>
</html>

Categories

Resources