I am still new to Javascript and I need help on how to display all even numbers in a single alert box. When I run the code, it only displays "21".
function myFunction() {
var i;
for (i = 2; i <= 20; i++) {
if (i % 2 == 0);
}
alert(i);
}
<h2>Even numbers from two to twenty</h2>
<button onclick="myFunction()">Display</button>
The value of i changes everytime the code in the loop is run.
By the time your code gets to the alert() function, the value of i is equal to the last uneven number you encountered.
A way of solving this is by adding all the uneven numbers to an array and then alerting the value of this array.
Like this:
<h2>Even numbers from two to twenty</h2>
<button onclick="myFunction()">Display</button>
<script>
function myFunction(){
var i;
uneven = [];
for (i=2;i<=20;i++){
if(i%2!=0){
uneven.push(i);
}
}
alert(uneven);
}
</script>
Every time the loop encounters a number that's uneven, it is added to an array. In the end the array will be a list of uneven numbers.
If you put this list in the alert() function, you'll get all the uneven numbers.
The modulus operator % also checks the remainder after a division. If the remainder after a division by 2 is 0, the number is even. Therefore you should add i to the uneven numbers when i%2 != 0. So when it's not even.
Your syntax is wrong. You have alert(i); after for loop is ended. So once forloop is finished i = 21.
so change it to
for (i=2;i<=20;i++)
{
if(i%2==0) {
alert(i);
}
}
}
<h2>Even numbers from two to twenty</h2>
<button onclick="myFunction()">Display</button>
<script>
function myFunction()
{
var i;
var evenNo=[];
for (i=2;i<=20;i++)
{
if(i%2==0)
evenNo.push(i);
}
alert(evenNo.join(", "));
}
</script>
Related
I currently have this small script that outputs a value after each iteration of a while loop:
var i = 0;
var number = "";
while (i < 10) {
number += console.log(i);
i++;
}
Which creates this output:
0
1
2
3
4
5
6
7
8
9
However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
i++;
}
I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
API_Send(number)
i++;
}
What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.
I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?
The problem is that you have declared number as string, don't do that just assign 0 to number variable.
Because of string variable javascript is concatenating the numbers.
Change as following:
var i = 0;
var number = 0;
while (i < 10) {
number += (i);
console.log(number)
i++;
}
I'm a newbie to Javascript so please bear with me for this basic question,
I'm trying to get my function to add all the individual digits in a string together, and then keep doing this until I'm left with a single digit!
3253611569939992595156
113 // result of the above digits all added together
5 //result of 1+1+3
I've created a while loop, but it only adds the numbers together once, it dosn't repeat until a single digit and I can't work out why!
function rootFunc(n) {
var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number
while (splite.length > 1) {
splite = splite.reduce(getSum);
}
return splite;
}
console.log(rootFunc(325361156993999259515));
function getSum(total, num) {
return total + num;
}
You're reducing properly, but what you're not doing is re-splitting. Try breaking this out into separate functions:
function digits(n) {
return n.toString().split('').map(x =>Number(x));
}
Then split each time:
function rootFunc(n) {
var d = digits(n);
while (d.length > 1) {
d = digits(d.reduce(getSum));
}
return d;
}
The problem here is that you return the result after the first splice. You need to have a recursive function. To do this, you can put this before the return :
if(splite > 9) splite = rootFunc(splite);
This way, you check if the result is greater than 10, if not you do the function with the remaining digits
I was looking this over in jsfiddle, and your number isn't being passed to exact precision, so just console logging n as soon as you call rootFunc, you've already lost data. Otherwise, to fix your loop, you need to remap splite to a string before the end of your codeblock since your while statement is checking .length, which needs to be called on a string. Put this piece of code at the end of the block:
splite = splite.toString().split('').map(x =>Number(x));
I have below javascript code with loop but I can't get the average of it. I'm not sure what's wrong with my code. It's like the first prompt you will input a number and it will loop and you input numbers like how much you entered and you will get the sum of all the numbers and get the average of it after it's done. Here's the code that I have.
function show_prompt()
{
var n=prompt("Input a number: ", "Number here");
if (n==n)
{
var i=1;
do
{
var g=prompt("Input grade: " );
var grade=parseInt(g);
var total=grade+grade;
i++;
}
while(i<=n);
}
var average=(total)/n;
document.write("Average is: " +average);
}
Thanks in advance!
You are overriding your "total" variable in each interval with double the grade value.
var grade=parseInt(g);
var total=grade+grade;
should be changed to
var grade=parseInt(g);
total=total+grade;
Also, you need to initialize the "total" variable in the beginning of your code.
See demo code: http://jsfiddle.net/56ouvan3/1/
I would also recommend some input validation (such as checking that the number of grades requested to average are greater than 0, all grades are positive, etc.)
I think you wanted to accomplish something like that:
http://jsfiddle.net/3L8dL228/1/
Just replace the console.log with your own document.write.
Now, despite I totally hate using prompts and I'm not very used to them, here are you what I think you're missing in your script:
CONTROL: your "n" and "g" variables HAS to be an integers, so force the user to insert an integer.
Variables declaration: you're declaring total every single time you loop, therefore you're not storing anything at all.
To fix these, the very first piece of your code becomes this:
var n = prompt("Input a number: ", "Number here");
while (!parseInt(n) )
{
n=prompt("Input a number: ", "Number here");
}
In this way, you're asking the user to give you a NUMBER, but the script won't procede until it will effectively be able to parse an integer value.
Therefore, inputs like "hey", "hello", "foo", "bar", "baz" won't be accepted.
The second part of your code then becomes this one:
var i=1;
var total = 0;
do
{
var g = prompt("Input grade: " );
while (!parseInt(g)) {
g = prompt("Input grade: " );
}
var grade = parseInt(g);
total += grade;
i++;
}
while(i<=n);
var average=(total)/n;
console.log("Average is: " +average);
and console.log needs to be document.write in your case, but for testing purposes and because jsfiddle (of course) doesn't allow document.write you need to check your console to see the correct value.
What changes from your script to this one is that we are declaring total as a global variable, not as a local variable inside the do loop that will be reset each time you loop.
Next, we're using the same logic as the first prompt for the second one, because you want, again, an integer value, not a possible string like "hey".
After that, we're ADDING that value to the total variable, by not redeclaring it.
Finally, after the loop, we're dividing that global variable total by the global variable n, getting the average.
Try below code to get the average of the entered number.
numGrades = prompt("Enter number of grades to be entered: ");
//number of grades to be entered LOOP
for (index = 1; index <= numGrades; index++) {
numberGrades = prompt("Enter Grade " + index);
}
//Calculation
gradePointAverage = numberGrades / numGrades;
document.write("Your GPA is " + gradePointAverage );
I've done FizzBuzz several times but never had this problem. Perhaps, it is something fundamental about for-loops that I don't understand. For some reason, the code below runs 10x longer than it should (well, than I think it should). If the user enters 20, it runs to 200. I fixed the problem by setting i = 0; i < num and then printing i+1 to my div, but I still don't understand why the original code does not work as expected. And while I'm at it, I might as well admit that I still can't set up JSFiddle properly. http://jsfiddle.net/nngrey/hA4pg/ (This does not run at all.) So any thoughts on that would also be appreciated. Thanks!
<head>
<title>Fizz Buzz</title>
<script>
function fizzbuzz(){
var num = prompt("Please enter a number between 1 and 100: ");
for(var i=1; i<num+1; i++){
if (i%3===0 && i%5===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Fizz Buzz</p>";
}else if (i%3===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Fizz</p>";
}else if (i%5===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Buzz</p>";
}else{
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>"+i+"</p>";
}
}
}
</script>
</head>
<body onLoad = "fizzbuzz()">
<div id = "div1">
<h1>Fizz Buzz</h1>
</div>
</body>
In your code, prompt() returns a string. Javascript will evaluate this line:
for(var i=1; i<num+1; i++){
with num as a string. i.e num+1 becomes "20"+"1" (note the quotes) which is "201". the comparison is then evaluated numerically, so your loop runs ten times linger than it should.
In your revised version i < num is evaluated numerically, so the loop runs for the correct period.
You can force num to be a number like this:
var num = Number(prompt("Please enter a number between 1 and 100: "));
num is now a number, so 20 + 1 = 21 (note - no quotes) and both versions of your loop should operate correctly
You need to do:
var num = parseInt(prompt("Please enter a number between 1 and 100: "), 0);
prompt returns a string, so if you enter 20, num+1 is the string "201", not the number 21.
here num is a string you have to use parseInt to convert it to int
for(var i=1; i<parseInt(num)+1; i++){
}
The prompt() returns a string.
Simple use +prompt() instead. That should make it a number. Updated code demo.
Each string in an array is a number, for example array1 = ["1296", "12", "27"];
For each string above, if possible to divide by 6 evenly without remainders, I want to do so at least once, then if the result is still longer than 2 characters, repeat. Then replace the string in the same position, such that the array would become ["36", "2", "27"];
so far, my code partly works.
w=0;
function divideBySix(){
if ((array1[w] / 6) == (Math.floor(array1[w] / 6))) {
var temp = array1[w] / 6;
array1[w] = temp.toString();
if (array1[w].length < 3) {
w++;
}
divideBySix();
}
The function successfully divides the first string by 6 once, and then calls itself again and again until the result is within 2 chars long. At that point, it should continue calling itself, and do the same to the next string of the array. But it doesn't do the next string. I don't know why it stops after finishing the first string. So the array looks like this ["36", "12", "27"]; Also, w successfully gets incremented. So I know its getting at least that far...
The function you give has unbalanced { }. When I add one at the end and run it, I get the result you say you want — ["36", "2", "27"]. There must be something else wrong, or you have not copied the code correctly.
In order to understand the operation, I added this to the beginning of divideBySix:
console.log(w, array1.toString());
i think you could just go with the modulo operator, if this is what you wanted to achieve
if(array1[w] % 6 == 0) doSomething()
and to solve your current problem you could introduce a second function ; for me it works with :
function divideBySix(array){
for(var i = 0; i < array.length; i++){
array[i] = divideNumber(array[i], 0);
}
}
function divideNumber(nr, ct){
if((ct < 1 || nr > 99) && nr%6 == 0 ) return divideNumber(nr/6, ct+1);
else return nr;
}
var array1 = ["1296", "12", "27"];
divideBySix(array1);
alert(array1);
When I test the code, that's what it does:
http://jsfiddle.net/Guffa/x4fNP/