user input output multiplication table - javascript

I need to make a multiplication table that displays the users input from 1-9, so if they enter 3 it will display the multiplication table for 3 from 1-9. it must do this with each number.
I have a for loop working for only 1 number and I dont know what else to do, I'm still really new to this so I'm not sure how to make it work for me.
prompt ("please enter a number");
var a = 1;
var b;
for (var i = 1; i <= 9; i++){
b= a*i
document.write("" + a + "*" + i + "=", + b +"<br>");
}
If I enter any number from 1-9 it must display the multiplication from 1-9 for that one number. Must work for each number entered.

the variable a should have the value received from the prompt and not 1
var a = prompt ("please enter a number");
var b;
for (var i = 1; i <= 9; i++){
b= a*i
document.write("" + a + "*" + i + "=", + b +"<br>");
}

You need to create variable for the prompt and add it inside your document.write
var question = prompt("please enter a number");
var a = 1;
var b;
for (var i = 1; i <= 9; i++) {
b = a * i
document.write(question + " " + "* " + i + " " + " = ", + b + "<br>");
}

You have to assign the return of the prompt function to your a variable.
Also, you have to cast this string value to a number to make sure your calculations are correct.
In the snippet below:
I wrapped the call to prompt with the Number function to get a number (MDN doc about Number).
I changed the var keywords to let and const as this is preferred over var, which declares global variables.
I replaced the string concatenation with a template string, which is easier to read when building complex strings (MDN doc on template literals).
const a = Number(prompt('please enter a number'));
for (let i = 1; i <= 9; i++) {
const b = a * i;
document.write(`${a} * ${i} = ${b}<br>`);
}

Related

Javascript median using for

So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".
function Media()
{
var n = prompt("number of elements?");
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong
You should parse the result of prompt to an integer;
How to convert a string to an integer in JavaScript?
function Media() {
var n = parseInt(prompt("number of elements?"));
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
m = parseInt(m);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
Media();
<div id='rezultat' />
You should also parse the result of prompt using parseInt
var m = parseInt(prompt("insert # " + i));
s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.

Javascript how to make a loop to display ten division calculations without reminder

I'm trying to make a script for kids to practice math. I managed to make +, -, x but can't complete divisions. Project can be seen here:
http://fibeeland.com/projects/math_tasks/index.html
I'm taking random numbers from the inputs and generate tasks. How to make division calculations so only examples with no reminder are shown?
my function looks like this:
//get a random number
function randomNumber(){
var minNumberId = document.getElementById("minNrId");
var xx=minNumberId.value;
var maxNumberId = document.getElementById("maxNrId");
var yy=maxNumberId.value;
var min = Math.ceil(xx);
var max = Math.floor(yy);
var randNr1 = Math.floor(Math.random() * (max - min + 1)) + min;
return randNr1;
}
function division(min,max,tasks){
document.getElementById('division_loop').innerHTML = " ";
var tasks_quantity = document.getElementById("tasks_quantity");
var tasks = tasks_quantity.value;
for (i=0; i < tasks; i++){
var a = randomNumber();
var b = randomNumber();
if((a%b)===0){
document.getElementById('division_loop').innerHTML += "<p><span class='task_punctuation'>" + (i+1) + ". </span>" + a + " / " + b +" = <input type='text' class='answerInput' id='" + (a/b) + "'></p>";
} else{
b = 2;
document.getElementById('division_loop').innerHTML += "<p><span class='task_punctuation'>" + (i+1) + ". </span>" + a + " / " + b +" = <input type='text' class='answerInput' id='" + (a/b) + "'></p>";
}
}
$(".answerInput").keyup(function() {
var InputID = this.id;
value = $(this).val();
//change to lower case
var InputIDlow = InputID.toLowerCase();
var valuelow = value.toLowerCase();
if(valuelow==InputIDlow){
$(this).css('background-color', '#bcffb9');
}
else{
$(this).css('background-color', '#dbdbf4');
}
});
}
division();
Thank you in advance.
Matt
Okay your script seems to work if a is divisible by 2. You can check if that's the case and if not just add 1 to a.
That seems to be pretty boring for the kids :D
What about choosing a random number (just one)
For example b = 3
Then you can multiply that by a random number (you might wanna reduce the range so that the multiplication is within the bounds).
Then just say your result is a and then you just ask for a/b.
Example
b = randomNumber()
a = b*randomNumber() # adjusting the range
Then just as usually ask for a/b

Addition Assignment confusion, again JavaScript

According to Mozilla, the Addition Assignment operator
adds the value of the right operand to a variable
and assigns the result to the variable. The types of the two operands determine the behavior of the addition.
Here's the behavior of the addition:
If both expressions are numeric, then add.
If both expressions are strings, then concatenate.
If expression is numeric and the other is a string , then concatenate.
Basically, text+=i is the same as text = text + i; that is a fact.
Ok, if the above is true, then why in Code Version 2 below when I variable-ize the string "The number is " to the variable text,
doesn't it write the string each time with the new number as code version 1 does?
And for the answer I don't want another way to write it. I need to figure out why it doesn't work the same way if text+=i is the same as text = text + i.
I'm getting better at JavaScript every day, but believe it or not this simple += is holding me back from further understanding it because too many examples are using +=.
Here is the Code Version 1:
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Here is the Code Version 2 with var text variable-ized with the string "The number is ":
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text ="The number is ";
var i;
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
You are writing different code.
a = a + b is indeed the same as a += b.
var text = "";
text += "The number is " + i + "<br>";
Is the same as:
var text = "";
text = text + "The number is " + i + "<br>";
But it's not the same as:
var text = "The number is ";
text = text + i + "<br>";
Which is what you had.
For a question like this, it can be very helpful to use console.log to see what is happening.
var text ="";
var i;
console.log("First approach");
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
console.log("Second approach");
text ="The number is ";
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
The code runs differently because in the first case you concatenate the entire string of "The number is ..." and in the second case, you initialize the string with "The number is " and then only concatenate the digits.

JavaScript Calculator - scope?

I am relatively new to JS, and trying to create a JavaScript calculator that takes a number and then uses the operator with a second number to create a total. Then I could use another operator on that total with another number, and so on, until the clear button is pressed. My biggest problem seems to be with the scope of my variables. At the moment I created a stopgap, that will add and subtract one digit numbers. Is there a reason why this code won't at least multiply and divide single numbers?
My other idea is to create two variables with empty arrays for the two numbers that will be used, so that as each active button is pressed you can push it into the specific array, which I think would solve the problem of only using single digit numbers, right? Thanks in advance! Just trying to learn and keep getting better!
// Calculator
var number = '';
var newNumber = '';
var operator = '';
var totalVal = '';
var result = '';
var inputCount = 0;
// Adds clicked numbers to the number variable and then sets value to totalVal
$('.numbers').on('click', function(){
if(result == ''){
inputCount++;
if (inputCount < 2){
number += $(this).text();
$('.inner-screen').text(number);
result = number;
console.log("number: " + number);
console.log("result: " + result);
} else {
newNumber = $(this).text();
}
// number = '';
} else{
newNumber += $(this).text();
$('.inner-screen').text(newNumber);
}
console.log("number: " + number + ", newNumber: " + newNumber);
});
$('.operators').on('click', function(){
operator = $(this).text();
console.log(operator);
$('.inner-screen').text('');
});
// Resets all the variables when clear button is clicked
$('.clear').on('click', function(){
number = '';
result = '';
newNumber = '';
operator = '';
totalVal = '';
inputCount = 0;
console.log('Clear Button Worked!');
$('.inner-screen').text('');
});
$('.eval').on('click', function(){
console.log("num1: " + number + ", operator: " + operator + ", num2: " + newNumber);
if (operator === " + "){
result = parseFloat(newNumber) + parseFloat(number);
console.log(result);
} else if (operator === " - "){
result = parseFloat(number) - parseFloat(newNumber);
console.log(totalVal);
} else if (operator === " X "){
result = parseFloat(newNumber) * parseFloat(number);
console.log(result);
} else if (operator === " / "){
result = parseFloat(number) / parseFloat(newNumber);
console.log(result);
} else {
console.log("didn't catch");
}
$('.inner-screen').text(result);
number = '';
newNumber = '';
});
Is there a reason why this code won't at least multiply and divide single numbers?
Right-o. I see what's going on.
Once you've pressed eval, you need to remember some state:
number = result;
result = '';
newNumber = '';
operator = '';
inputCount = 1;
Old version:
http://jsfiddle.net/xjegrp58/
New version, with state added to the eval function:
http://jsfiddle.net/axLhcawf/
Try this on each:
2 * 2 = 4, then * 2 to get 8

Find greatest value in array (in set of integers)

My friend asked me to help him with homework, and I'm stuck. Here is assignment:
user must enter in first prompt box number of elements in array. Then, he will get prompt box for each number to enter. Now, output must be greatest number in array. But that simply doesn't work. With my code below, I always get the element who has greatest first digit. (it's doesn't matter if number is negative or positive, code doesn't work as it should)
Here is my code (it even doesn't work in jsfiddle, just in my file)
<button onclick="duzinaNiza()">Do it!</button>
and here is JavaScript
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:");
\\ prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
My friend's proffesor doesn't want to use functions for sorting arrays, this must be done with loops.
P.S. Yeah, I know... But don't ask about document.write thing, it must be printed in that way...
That is because the input is a String, you have to parse it to a Integer. Like:
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
Try this:
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"));
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
The problem is that you are comparing two strings, when you wanted to compare two numbers.
In other words, the following expression is LEGAL in javascript and evaluates to true:
if('4' > '393939393'){
//true! string '4' is greater than string '3' (first char of '393939393')
}
What you should do is cast the value received from the function prompt, so it is treated as a number. You can do that using the following function:
parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
The first parameter is the value you want to cast to a number, while the second is the radix (or "base") of the number.
So, the main problem here is that you're not threat your numbers as "number", but as string. The method prompt returns a string, so you need to convert them:
function duzinaNiza() {
var brClanova = +prompt("Enter the number of array elements:");
if (!brClanova)
return;
var niz = [];
for (var i=0; i < brClanova; i++) {
var redniBr = i + 1;
niz[i] = +prompt("Enter "+ redniBr + ". array number:");
}
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
}
I used the Unary Plus Operator for that.
Just for to know, in JS you can actually avoid the last loop using Math.max to get the maximum of an array of numbers. So instead of:
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
You will have:
var max = Math.max.apply(null, niz);
document.write("Greatest value in array is: " + max);
In that case, you don't even need the unary plus operator because Math.max takes care of that.
try this out, [Tip: i just utilised the '+' operator for casting the value to number (values from prompt.). The '+' operator will return NaN, if the entered value could not get converted into a number. so in that situation, you should use isNan function to get rid of that.]
duzinaNiza = function () {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
var maximum;
for (i=0; i<brClanova; i++) {
var temp = +prompt("Enter "+ i+1 +". number:");
if(i===0) { maximum = temp }
else { maximum = (temp > maximum)?temp:maximum; }
}
alert("Greatest value in array is: " + maximum);
}
}
You don't need parseInt- if you subtract strings that can be converted to numbers, they are converted. So you can subtract the maximum from the next number, and see if it leaves a remainder.
Also, parseInt will destroy decimals, so you won't know that 1.5 is greater than 1.
Your comment used the wrong characters- `('\' should be '//')
function duzinaNiza(){
var brClanova= prompt("Enter the number of array elements:");
if(brClanova>0){
var niz= new Array();
for(var i= 0;i<brClanova;i++){
var redniBr= i+1;
niz[i]= prompt("Enter "+ redniBr +". array number:");
//prompt for geting each array element
}
var maximum= niz[0];
for(var a= 0;a<brClanova;a++){
if(niz[a]-maximum>0){
maximum= niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
Modified Code JSFIDDLE
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:")*1; //convert string to intger
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:")*1;
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}

Categories