How to write and call functions in javascript with for loops? - javascript

I am working on writing code for a course and need to figure out why the code output is not executing properly. I am very new to coding, this is a beginner assignment so all help and explanations are greatly appreciated.
The output should look like this:
Output:
How many times to repeat? 2
Stats Solver execution 1 ====================
give a number 10.10203
give a number 20
give a number 30
give a number 40
give a number 50
sum: 150.10203
average: 30.020406
max: 50
min: 10.10203
ratio: 4.94
Stats Solver execution 2 ====================
give a number 3.21
give a number 2.1
give a number 1
give a number 5.4321
give a number 4.321
sum: 16.0631
average: 3.21262
max: 5.4321
min: 1
ratio: 5.43
done ====================
Here is the code:
"use strict";
function myMain() {
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
}
function wall(){
var num1 = Number(prompt("provide a number"));
var num2 = Number(prompt("provide a second number"));
var num3 = Number(prompt("provide a third number"));
var num4 = Number(prompt("provide a fourth number"));
var num5 = Number(prompt("provide a fifth number"));
var sum = (num1+num2+num3+num4+num5);
alert("sum: " + sum);
var avg = (sum/5);
alert("average: " + avg);
var max = (Math.max(num1,num2,num3,num4,num5));
alert("max: " + max);
var min = (Math.min(num1,num2,num3,num4,num5));
alert("min: " + min);
var ratio = (max/min);
alert("ratio: " + Math.floor(ratio*100)/100);
}
myMain();

Well you really aren't very far off at all. Actually your solution has all the code you need just some of it is in the wrong place. I would have posted this as a comment but as this is a new work account I can't actually post comments so here is a full solution with the explanations.
Your wall function, while annoying with all the alerts is actually correct and doesn't need any adjustments. With that said you might want to play with parseInt and parseFloat to make sure you are getting valid numbers but I am assuming that is outside of the scope of the assignment.
Now on to your main function.
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
This is ok and will prompt the user for a number, once again you might want to test that you got a valid number using the aforementioned links.
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This is where things start to fall apart a bit and where i think you are having problems. So I will break this down line for line and explain what each line is doing and you can compare that to what you think its doing.
var count = num;
Nothing crazy here, you are just creating another variable to hold the value in the num variable. Slightly redundant but not really a big deal.
for (var a=0; a<=num; a++) {count++;}
This is the line that appears to have given you the most confusion. This is the actual loop but inside the body of the loop { .... } nothing is being done except 1 is being added to count (count++). If I am understanding the assignment correctly, inside this loop is where you need to call your wall function after alerting the 'Stats Solver execution .....' stuff. All you need to do is move your function call inside this loop.
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This part is clearly you a little lost and just trying things to get it to work, don't worry even after 12+ years of development i still write code like this ;). You really don't need this as the actual call to wall() will work fine for you.
I am bored and am waiting on work so for the sake of being a complete answer here is an example of how your code should look. Please don't just hand this in rather try and actually understand the difference between what i wrote and what you did because these are some very basic concepts that if you gloss over will make your life much harder down the road. Always feel free to ask, thats how people learn.
function myMain(){
// get the number of repetitions from the user and cast as a number
var num = Number(prompt('Please enter the number of times to repeat'));
// loop from 0 to the number the user provided - 1 hence the <
for (var i = 0; i < num; i++){
// alert the iteration of the loop, you will notice i add 1 to num when we alert it; this is because it starts at 0 so the first time it displays it would show 'Stats Solver execution 0 ======' instead of 'Stats Solver execution 1 ======'
alert('Stats Solver execution ' + (num + 1) + ' ===============');
// call your wall function
wall();
// go back to the top of the loop
}
// alert that we are done.
alert('done===============')
}
// your wall function goes here
// call your myMain function to kick everything off
myMain();
Just for fun you might want to look at console.log instead of alert to not make it such an annoying process with all the popups.
If i missed anything or you are confused about anything don't hesitate to ask and i'll do my best to answer.

Related

JavasScript Add half a percent to a number any amount of times I choose

Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))

Show the average of the 1-digit numbers entered

I have a problem with the following exercise:
Enter N number of numbers by prompt. Show the average of the 1-digit numbers entered. End the program with the word “exit"/"salir”.
I also have to do the average calculation with a function. Here's what I have:
let i;
var sum = 0;
var avg = 0;
var average = function(i) {
sum = sum + i;
avg = sum/(i+1);
}
do {
i = prompt("Ingrese un numero: ");
if ((i < 10) && (i > -10)) {
average(i);
}
} while (i !== "salir");
alert(`el promedio de los numeros de un solo digito es: ${avg}`);
I tried limiting the program by stating that the average function will only be executed for one digit numbers, but the problem is that this is giving me the total average of all the numbers entered not the average of only the 1 digit numbers.
You've succeeded in avoiding including multi-digit numbers from the sum and average. The problem isn't in that, it's here:
avg = sum/(i+1);
That's not how averages work. An average is the sum divided by how many values went into making that sum. (The number of numbers you added to sum.)
Keep track of how many numbers you added to sum, and use that count to calculate the average.
Side note: A couple of notes on the code, just for what they're worth:
Your code is currently relying on implicit conversion from string (what the user types in) to number (what you use with sum). Although it works in this example, I strongly recommend doing the conversion explicitly. My other answer here (also on SO) lists your various options for doing that.
You've used both let and var in your code. I suggest never using var, it has no place anymore in modern JavaScript. Use let if you need to let the variable's value change (as with sum), and const when you don't.
You're missing one ; (after the assignment statement assigning to average). (You can rely on Automatic Semicolon Insertion if you like [I don't recommend relying on it, but some others do], but whichever way you go, it's best to know the rules and then consistently do or don't include your ;.)
I suggest declaring your variables in the innermost scope you can declare them in. There's no reason for i to be global in your code, just make it local to the do-while loop body.
Obviously in a very simple exercise like this it's mostly fine, but I recommend not getting used to prompt and alert, they're relics from the 1990s and behave in very unusual (and sometimes problematic) ways compared to most functions in JavaScript.
var i;
var sum = 0;
var avg = 0;
var average = function(num) {
sum = sum + num;
i+=1
avg = sum/i;
}
var ans;
do {
ans = prompt("Ingrese un numero: ");
if ((ans < 10) && (ans > -10)) {
average(ans);
}
} while (ans !== "salir");
alert(`el promedio de los numeros de un solo digito es: ${avg}`);
Should remove this but will leave it here for any future visitors.

How to create number suffixes such as "100K" without having to be repetitive?

I've been having a problem that when my auto clicker in my clicker game goes fast enough to get to 200 thousand, it starts to lag, and then it doesn't function properly, or as fast.
Is there a way to make 100 thousand turn into 100K, and 101 thousand turn into 101K without being repetitive?
I tried this with my original code, and realized putting up to 1000 suffixes into each function would be a little too hard:
if (number >= 100000) {
document.getElementById(ID).innerHTML = "100K"
}
if (number >= 101000) {
document.getElementById(ID).innerHTML = "101K"
}
and on and on.
I don't want multiple if statements!
This would work, but it would take up way too much space, and I know there is an easier way to it, but I just couldn't find it. Can anyone provide a way to do this?
Try separating the job of formatting your number into a different function.
SUFFIXES = 'KMBTqQsSOND' // or whatever you'd like them to be
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3);
num = Math.round(num / Math.pow(10, (index * 3))); // first 3 digits of the number
return num + (SUFFIXES[index - 1] || ''); // default to no suffix if we get an out of bounds index
}
You can call the function like this: var x = getSuffixedNumber(101000), the value of x will be "101K".

Score counter doesn't count scores properly

First off, I have to say that I am very new to Javascript and programming in general so it's possible that the issue is related to my (current) lack of knowledge.
I've tried to make a simple game where a computer thinks of a random number between 0 and 10 and the user tries to guess that number by typing his guess in the text field. If the number is correct, the user gets the message that they guessed the number correctly and otherwise, they get the message that the numbers are not correct.
The first part works as intended. The problem is the score counter.
So this is the part of the HTML code that I wrote for the counter:
<p id="points">Number of points: </p><span id="points-number">0</span>
And this is the code that I wrote in JS:
<script type="text/javascript">
document.getElementById("instructions").onclick = function() {
alert("You need to guess the number that your computer imagined. Viable numbers are between 0 and 10. Every time you guess the number, score increases by 1 and every time you miss, you will lose a point")
}
document.getElementById("guess-number").onclick = function() {
var ourNumber;
var randomNumber;
var pointsNumber = 0;
randomNumber = Math.floor(Math.random() * 10);
ourNumber = document.getElementById("input").value;
if (ourNumber == randomNumber) {
alert("The numbers are equal!");
pointsNumber+=1;
var result = document.getElementById("points-number");
result.innerHTML = pointsNumber;
} else {
alert("The numbers are not equal! The number that your computer imagined is:" + randomNumber + ", and our number is: " + ourNumber);
pointsNumber-=1;
var result = document.getElementById("points-number");
result.innerHTML = pointsNumber;
}
}
</script>
Now here's the problem...whenever the user misses the number, the number of points goes to -1. But if he misses the second time, it stays at -1, it doesn't decrease further. After the user guesses the number, the value changes from -1 to 1. But, if he guesses again, it doesn't increase to 2, it stays at 1. Then when he misses, it jumps back to -1 and vice versa.
So, I believe I am missing something here, what should I do to make the counter work as intended? In other words, to make the score increase by 1 every time the user guesses the random number and make it decrease by 1 every time he doesn't get it right?
Thanks in advance.
basically, you are always starting with
var pointsNumber = 0;
instead, you should use:
var pointsNumber = + document.getElementById("points-number").innerHTML;
bonus:
and yes instead of:
randomNumber = Math.floor(Math.random() * 10);
use:
randomNumber = Math.floor(Math.random() * 11);
because, Math.random() lies between 0 (inclusive) and 1 (EXCLUSIVE), so could never reach 10.
see more about Math.random() at: https://www.w3schools.com/js/js_random.asp
You need to declare pointsNumber outside of the function:
var pointsNumber = 0;
document.getElementById("guess-number").onclick = function() {
var ourNumber;
var randomNumber;
Otherwise, each time the onclick function is called, you declare pointsNumber and set it to 0. Then it gets +1 or -1 depending on the if/else, which explains the behavior you are observing.

JavaScript For Loop with user entry error

I am currently dabbling with JavaScript and am doing some simple calculations using for loops and I am attempting to take user info for the Table set they want and the numbers they wish to multiply between e.g.
Enter Table set: 12
Enter where to start multiplying from: 3
Enter how high to multiply: 6
This would print:
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
My issue is that when I ask the user to select how high they wish to multiply to, if they select a number greater than 9 it doesn't enter the for loop and prints nothing yet 9 and below works.
This is the simple enough code:
function UserEnteredTables()
{
var tableNumber = prompt("Please enter the number tables to use: ");
var numberLowerLimit = prompt("Please select where you want to start multiplying from: ");
var numberUpperLimit = prompt("Please select how high to multiply to: ");
document.write("Before the loop " + numberUpperLimit + "<br/>");
for (i = numberLowerLimit; i <= numberUpperLimit; i++)
{
document.write("Made it inside the loop " + "<br/>");
document.write(tableNumber + " * " + i + " = " + (i * tableNumber) + "<br/>");
}
document.write("After the loop " + numberUpperLimit);
}
Apologies for any indentation issues, had issues pasting for some reason
I have attached two images, one where I enter the upper limit to 9 and then one were I enter 10. As you can see the 10 doesn't enter the loop.
I assume that I have missed something very simple but I would appreciate if someone could explain what the issue is or if its something to do with JavaScript loops.
If there is something wrong with the post or you require some other code to fully understand just let me know.
Thanks in advance :)
The issue is with the prompt value returned: its typeof is string, while what you want is number for the loop to work correctly.
Use parse() to extract the numeric value out of the prompt value, see here:
https://jsfiddle.net/jwvj2aab/1/
Note that you will need to handle user input in order to deny anything but numbers

Categories

Resources