Run a loop n times - javascript

I'm writing a program that will calculate a number entered by the user multiplied by 2.
I realised I need a for loop so that the Value will increment by 1 and multiple by 2
The problem is I want to know how to run this loop only 10 times
- at the current moment it will run for ever and I had to place an if statement to break out of the loop if the value reaches 50.
//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (value;; value++) {
value2 = value * 2;
document.write(`${value} multiply 2 -> ${value2}`);
document.write('<br>');
//i placed this if statement to break out of the for loop as it //will run forever
if (value > 50) {
break;
}
}

you can use a counter variable to keep a check on number of iterations. I am guessing you want to increase value by 1 after each iteration. You can do something like this:
//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (var i=1;i<=10; i++) {
value2 = value * 2;
document.write(`${value} multiply 2 -> ${value2}`);
document.write('<br>');
//i placed this if statement to break out of the for loop as it //will run forever
value++;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--
<script type="text/javascript" src="js.js"></script>
-->
</head>
<body></body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>Multiple By 2</h2>
<input type="text" id="num"/>
<button onclick="multiply()">multiply by 2</button>
<script>
function multiply() {
var number = document.getElementById("num").value;
for(i=1;i<11;i++){
console.log(number*i);
}
}
</script>
</body>
</html>

Related

What can I do to resolve this error code isssue?

Use the prompt() method to ask the user what the maximum number should be. The prompt should be in a loop with validation as demonstrated previously in the course making sure that the inputted value is a positive number. If the user inputs a decimal, simply round it.
When a valid number is inputted, change the content of the instructions to specify guesses between 1 and N.
When the user presses the guess button, validate the input:
If the guess is not a number, display a message: "That is not a number!"
If the guess is out of range (1 to N), display a message: "That number is not in range, try again."
Using an array, keep track of each guess by the user. When the user wins the game by guessing correctly, add the number of guesses and the list of guesses to the victory message. For example:
"You got it! It took you 5 tries and your guesses were 3, 14, 7, 9, 5"
Do not count invalid guesses (not numbers or out of range).
Since you are tracking the guesses, add validation to check if a number has already been guessed. If it has, display a message and do not count it as a guess.
HTML File:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<title>Higher - Lower</title>
</head>
<body>
<div class="container">
<h1>Higher Lower</h1>
<p>Guess a number between 1 and <span class="max-number">N</span></p>
<div class="row">
<div class="col-lg-3 cold-md-6">
<form>
<div class="form-group">
<label>Your guess:</label>
<input type="text" id="userInput" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick= "do_guess()">Guess</button>
</form>
</div>
</div>
<p id="message"></p>
</div>
<script src="HigherLowerEnhanced.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudfare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
JavaScript File:
let maxNumber;
// use an infinite loop that continues until a users input is validated
while (true) {
maxNumber = prompt("What should the maximum number be?");
// check if the user input is actually a number
if (isNaN(maxNumber)) {
// keeps the loop going until input is validated
continue;
}
// check if the number is a decimal
if (!Number.isInteger(maxNumber)) {
// function that rounds numbers
maxNumber = Math.round(maxNumber);
}
if (maxNumber < 1) {
console.log("Please Enter number more than 0");
continue;
}
// function to set the spans value to the input number
const maxNumberSpan = document.querySelector('.max-number');
maxNumberSpan.innerHTML = maxNumber;
break;
}
// generate random number between 1 and infinite
let num = Math.floor(Math.random() * maxNumber) + 1;
// function stores users guesses
const inputArray = [];
document.querySelector('.btn').addEventListener("click", (e) => {
// prevents page from refreshing after you click submit
e.preventDefault();
// call do_guess() function on click
do_guess();
});
// do_guess function
function do_guess() {
// get message div
let message = document.getElementById("message");
// get input value
let guess = Number(document.getElementById("guess").value);
// if input is not a number
if (isNaN(guess)) {
message.innerHTML = "This is not a number";
// return function (so that user can submit another number)
return;
}
// if number is out of range
if (guess < 1 || guess > maxNumber) {
// show this message
message.innerHTML = "That number is not in range, try again";
// return function
return;
}
// indexOf() function finds guess in inputArray
if (inputArray.indexOf(guess) != -1) {
// when the guessed number is not found in the array it will return -1
message.innerHTML = "You already have tried this number";
return;
}
// now we have checked validation of input push guessed number on array
inputArray.push(guess);
// if input is equal to num
if (guess == num) {
message.innerHTML = "You got it! It took you " + inputArray.length + " tries and your guesses were " + inputArray.toString();
}
// if guess is more
else if (guess > num) {
message.innerHTML = "No, try a lower number.";
}
// if guessed number is less
else {
message.innerHTML = "No, try a higher number.";
}
}
Error:
[Running] node "/Users/tonyjones/Desktop/HigherLowerEnhanced/HigherLowerEnhanced.js"
/Users/tonyjones/Desktop/HigherLowerEnhanced/HigherLowerEnhanced.js:6
maxNumber = prompt("What should the maximum number be?");
^
ReferenceError: prompt is not defined
at Object.<anonymous> (/Users/tonyjones/Desktop/HigherLowerEnhanced/HigherLowerEnhanced.js:6:9)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.1
[Done] exited with code=1 in 0.324 seconds
You are trying to use prompt. Node.js does not provide a native prompt function. Web browsers do.
Ditto the document object.
You have an HTML document. Node.js does not centre on HTML documents. Web browsers do.
Run your code in a web browser instead of in Node.js.

Javascript : multiple remainder pricing table

I have been given this logic table that I need to use if else statement to get a promotion price based on user input.
How to declare that logic table in javascript? So that I can print out the correct output based on the table.
For example; if user input is 5, so, I need an expected output of (price 3 + price 2).
function checkQuantity() {
let userInput = document.getElementById('quantity').value;
userInput = Number(userInput); //Convert string to number data type
var pizzaPrice = 6.45;
var pizzaPrice2 = 12.00;
var pizzaPrice3 = 14.00;
if (!userInput) {
console.log("Please enter a valid pizza quantity");
} else if (isNaN(userInput)) {
console.log("Error!!");
} else if (userInput < 1) {
console.log("Minimum pizza order is 1.");
} else {
document.getElementById('message').innerHTML = 'Number of pizza : ' + //Price hasn't been declared yet;
}
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
<script src="linked.js"></script>
</head>
<body>
<h1>PizzasOnly ordering form</h1>
<p>Simply enter the number of pizzas you want into the input below to find out the cost of your order</p>
<form action="#" method="post" id="orderForm" onsubmit="return checkQuantity()">
<p>
<label for="quantity">Enter number of pizzas wanted:</label>
<input name="quantity" id="quantity" value="">
</p>
<p>
<input value="Total cost" type="submit">
</p>
</form>
<div id="message"></div>
</body>
</html>
The formula can be assembled as a one-liner:
~~(i/3)*price + xtra[i%3]
~~ (the repeated application of the "bitwise NOT operator") is a shorthand notation for Math(floor(), % is the modulo operator that will return the remainder of a division, the rest should be clear.
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i)) )
In this later version I defined the function price(). It can be called with one argument (i: number of pizzas) as you can see above.
The optional arguments p3 (price for a bundle of 3) and xtr (addon for zero, one or two extra pizzas) can be supplied if you want to use a different pricing structure than the default one, see here:
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i,16,[0,6,11])) )

Number.IsNaN and not categorizing variable*number properly?

So I am trying to make the script recognize bad input and give no output
If I put any number each time I input something it runs the function Myfunction.
The function returns output in textarea id=t as the number inputted followed by the same number * 100 and *1000. When the input area id=1 is blank it triggers if statement as true because it checks isNaN which a blank area is, the value of id=t is then changed to blank, when I add just a letter or multiple letters to textarea id=1 it shows no input as it should. However if I input a number followed by any combination of letters in textarea id=1 it first updates output to match the number, then when the letters are typed the output doesn't change and is equal to that of inputting just the number before the letters, isNan doesn't register it as 1 and typeof doesn't register it as not a number type.
Why does this break, How do I fix this?
<!-- Unit converter iteration 2 -->
<head>
</head>
<body>
<!-- Input uses oninput event to execute function-->
<textarea type="number" oninput="return myFunction()" id="1" name="1" value="" rows="1" cols="30"></textarea><br>
<textarea readonly id="t" rows="5" cols="30"></textarea>
<script type= "application/javascript">
/*Instead of throwing alert if N is NaN, it doesn't show any output instead */
function myFunction(){
var N = parseInt(document.getElementById("1").value);
if (Number.isNaN(N) || typeof(N) != "number" ){
document.getElementById("t").value = "";}
else {
/* Outputs same variables as in iteration 1 but now the html form is textarea*/
var m = N;
var cm = m * 100;
var mm = m * 1000;
document.getElementById("t").value = ""+m+" "+cm+" "+mm;}
}
</script>
</body>
</html>
That's just because of how parseInt works. Let's focus on this part of your code:
var N = parseInt(document.getElementById("1").value);
if (Number.isNaN(N) || typeof(N) != "number" ){
document.getElementById("t").value = "";}
When parseInt is called on a string that starts with a number followed by characters (e.g. 123abc), the function will return the numbers as an integer (123 in the previous example).
Example:
num = parseInt('123abc');
console.log(num);

For Loop Only Running Through Once

In the following program, for some reason, the for loop runs through once, and then does not repeat. I believe the error is with the bold code. Help is very much appreciated. This is a program used to change a text box to caps, title case, etc. Title case being the first letter of each word capitalized. Thank you.
<html>
<head>
<script type="text/javascript">
function titlize(){
tLength=tBox.box.value.length
character=new Array()
for(i=1; i<tLength+1; i++){
**character[i]=tBox.box.value.slice(i-1,i)**
document.write(character[i])
if(i==1){
character[i]=character[i].toUpperCase()
}else if(character[i-1]==" "){
character[i]=character[i].toUpperCase()
}else{
character[i]=character[i].toLowerCase()
}
document.write(i)
document.write(character[i])
}
}
function upperC (){
toUpperCase(tBox.box.value)
}
function verify (){
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
if(tBox.lowercase.checked){
tBox.box.value=tBox.box.value.toLowerCase()
}
if(tBox.titlecase.checked){
titlize()
}
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
}
</script>
</head>
<body>
<form name="tBox">
<input type="text" name="box" value=""><br>
<input type="checkbox" name="uppercase" onClick=verify(this.form)>Uppercase<br>
<input type="checkbox" name="lowercase" onClick=verify(this.form)>Lowercase<br>
<input type="checkbox" name="titlecase" onClick=verify(this.form)>Titlecase<br>
</form>
</body>
</html>
tBox is your form not your textbox, so trying to get it's value and then the length of that value is not valid. The code needs to access your textbox, so it should be:
// Scan for the first textbox. Give that textbox a unique id to be
// able to write a more specific query.
tLength= document.querySelector("input[type='text']").value.length;
character=new Array()
// Not sure why you were writing: i < tLength +1 as that will
// cause your loop to go one character too far. Remember,
// arrays start from 0 and length starts from 1.
for(i=1; i < tLength; i++){
Lastly, avoid document.write() because if you use it on a document that has finished being parsed, it will cause the entire existing document to be thrown out.
Based on the code above. You have document.write statements in your function, which is causing issues in overwriting your DOM. I've removed those, and that will allow it to function normally. Also, I added tBox.box.value = character.join("") to put the text back into the text box.
https://plnkr.co/edit/qOPIxwH16hJUlj0RFBhv?p=preview
function titlize() {
tLength=tBox.box.value.length;
character=new Array();
for(i=1; i < tLength + 1; i++){
console.log('print')
character[i]= tBox.box.value.slice(i - 1,i)
//document.write(character[i])
if(i==1) {
character[i]=character[i].toUpperCase()
} else if(character[i-1]==" ") {
character[i] = character[i].toUpperCase()
} else {
character[i]=character[i].toLowerCase()
}
console.log(i)
console.log(character[i])
}
tBox.box.value = character.join("")
}

Javascript - Calculate average of numbers

pretty new here and in programming overall so I would really appreciate some help.
Now, I want to create a site that has a button which calls a function when clicked. This function brings up a prompt box that allows the user to insert numbers only, infinitely or until he clicks cancel on the prompt box or presses space.
When the insertion of the numbers has stopped, the function calculates the average of all the numbers inserted and displays the result on an alert box. I have tried it and here's my code so far.
<html>
<head>
<script type="text/javascript">
function calc_avg() {
var avg; var sum;var total;var num=1;
while (num>0) {
var x = parseInt(prompt("Please enter a number","0"))
if (x=="") {
break;
} else {
sum += x;
total++;
avg=sum/total;
window.alert(avg);
}
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="calc_avg()" value="Calculate Average">
</form>
</body>
</html>
Thanks in advance!

Categories