Creating a 'for' loop - javascript

I am trying to do an activity in my uni work and am having trouble getting the for loop to work. I have done the first stage using a while loop but I am getting stuck on the second stage.
My while loop -
var i=1;
while (i<=32) {
i = i*2;
document.writeln(+i +' ');
}
alert ('Wah-Lah!')

Your second part could be like that:
var sum = 0;
var k=1;
// 65 is too big !
for (i=1; i<30; i++)
{
sum += k;
k*=2;
document.writeln(+k +' ');
alert('Sum of all numbers = '+ sum);
document.writeln(' = ' + sum);
}

If you want to output the sum only, then you can just put the two lines, alert and doc.write outside the for loop

var sum = 0;
for (i=1; i<=64; i*=2) {
sum += i;
document.writeln(i);
}
document.writeln('sum: ' + sum);

You can modify your code the following way :
var sum=0;
for (i=1; i<65; i=i*2) {
sum += i;
document.writeln('' + i); //Displays values 1 2 4 8...
}
//Display Sum outside loop
document.writeln(' = ' + sum);

I'm not sure if I understand you well but in your for loop you are increasing you counter by 1, so in output you will get 1,2,3...,64. If you want to get output as 1,2,4,8... change your step argument to: i = i + 2. Finally your for loop should looks like:
for(i = 1; i < 65; i + 2)

Related

Ideas for how to catch the last index in a jscript for loop, where lengh of index is is unknown?

Consider the following for loop (and assuming we don't know 3 times table - i.e. how many results might occur).
<script summary>
function myFunction() {
var output_text = "";
var i;
for (i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if ("e.g. this is the last index?") {"e.g.then do this?"
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
}
</script>
Trying to 'output_text' as something like:
The number is 0
The number is 3
The number is 6
The number is 9
The number is 12
The number is 15
The number is the last 18
Any ideas for how to catch that last loop iteration.
This is just an example as actual application is a bit wordy - but the concept is the same.
I could run a count first to get index length, but wondered if there is an easier way.
Many thanks for anyone's time. Also first go at posting - any advice welcome.
Just add 3 to the current index and check if it exceeds 19.
function myFunction() {
var output_text = "";
var i;
const max = 19;
const factor = 3;
for (i = 0; i <= max; i++) {
if (i % factor === 0){
if (i + factor > max) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
return output_text;
}
document.write(myFunction());
If you have a number divisible by 3, perform a second check to see if 20 minus i < 3 and you'll know if it's the last number.
function myFunction() {
var output_text = "";
for (var i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if (20 - i < 3) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
document.getElementById("out").innerHTML = output_text;
}
myFunction();
<div id="out"></div>
The better approach is to show result of current iteration in the next iteration. In this case, last iteration will not be handled in the loop. So, you can handle it after easily.

What's the difference between document.write and the return statement?

So I wrote a function that generates 10 random numbers between 1 and 6, and I want to display the numbers on my HTML page, this is the Number Generate function :
function genereChiffre(){
var sResultat = "";
var iCompteur;
for(var i=0 ;i< 10 ;i++){
sResultat = Math.round(Math.random()* 6) + 1;
document.write("<li>" + sResultat + "</li>");
}}
This is the function to display the numbers :
(function (){
var aLesDiv = document.querySelectorAll("#global div");
aLesDiv[3].innerHTML = genereChiffre();
}) ();
What I don't understand is that when I use the document.write method and call the function as : genereChiffre() in the console, the 10 numbers are generated, but when I use a return statement as so
return("<li>" + sResultat + "</li>");
It only generates 1 number.
Try:
function genereChiffre(){
v
ar sResultat = "";
var _res
var iCompteur;
for(var i=0 ;i< 10 ;i++){
sResultat += "<li>" + Math.round(Math.random()* 6) + 1 + "</li>"
}
return(sResultat);
}
Because , you are stoping the for, when you are calling "return", now return the sum of all count from the for

Variable not looping properly

My program is supposed to take in an unknown amount of numbers and calculate the average to see if its >49 or <50. The problem occurs in the for loop. My sum isn't adding each mark and returns an undefined value. I have no idea why this is happening because the actual marks passes through the loop perfectly fine
var passingAverage = function ()
{
var sum;
var marks = arguments;
var average;
var i;
for (i =0; i<marks.length; i++)
{
sum += marks.length[i];
}
average = (sum/i);
if (average > 49)
{
return ("true");
}
else if (average < 50)
{
return ("false");
}
};
console.log('passingAverage(75,42,98) returns: ' + passingAverage(75,42,98));
console.log('passingAverage(34,93,77,89,49) returns: ' + passingAverage(34,93,77,89,49));
console.log('passingAverage(33,61) returns: ' + passingAverage(33,61));
console.log("\n");
I think you need to initalise sum. change var sum to var sum = 0;
sum += marks.length[i];
this is not the true way of calling an array elements
replace sum += marks.length[i]; with sum += marks[i]; , then the true sum gonna be calculated , and your average has a true value
be aware of the initial value of sum when you are defining it , it must be var sum = 0;
I've got the running code here: https://jsfiddle.net/bwcpps1v/
var passingAverage = function ()
{
var sum = 0;
var marks = Array.from(arguments);
var average;
var i;
for (i =0; i<marks.length; i++)
{
sum += marks[i];
}
average = (sum/marks.length);
if (average > 49)
{
return true;
} else if (average < 50) {
return false;
}
};
console.log('passingAverage(75,42,98) returns: ' + passingAverage(75,42,98));
console.log('passingAverage(34,93,77,89,49) returns: ' + passingAverage(34,93,77,89,49));
console.log('passingAverage(33,61) returns: ' + passingAverage(33,61));
A few observations:
You need to get better at debugging. Learn about Chrome Dev tools as a start to debugging JS. Step through your source watching key vars and you would have caught the earliest error faster.
Spend some time with a linter and also, indenting your code right using an IDE or decent text editor - it makes it easier to read and debug.

Changing div to lines with java script

The "output" div should be replaced with 10 lines of output. Each
line should display two numbers separated by a space. The first number should be the line number starting
with 1. So the numbers 1, 2, 3, 4... and so on. The second number should be the factorial of the line number.
(n factorial is 1 * 2 * 3 * ... * n.) That is, the numbers 1,
What should i use to create the list and to do the calculations. Tried using an array but was having difficulties in making the calculations. Any help would be appreciated
Check this one and try it
var result = '';
var lineno = 10;
for(j=1;j<=lineno;j++){
result = result + j + ' ' + fact(j) + '<br>';
}
document.getElementById("output").innerHTML = result;
function fact(n){
var i, no, fact;
f=1;
for(i=1; i<=n; i++)
{
f= f*i;
}
return f;
}
Link : https://jsfiddle.net/yrz46q85/
Counting factorial to 10 in 10 lines.
var output = document.getElementById("output");
var factorial = 1;
for(var i=1; i<=10; i++){
factorial = factorial * i;
output.innerHTML += i +". " + factorial + "</br>";
}
<div id="output"></div>

loop created element's value always 5

Can someone please tell me why when I click on the [s] href created next to the list of names (myhand) generated it always says selection and i are 5?
var printDD = function(myhand, mydiv){
var dtext = "";
for(var i = 0; i < myhand.length; i++){
dtext += '[s]' + myhand[i] + ', ';
}
mydiv.html(dtext);
for(var i = 0; i < myhand.length; i++){
$('#dd'+i).click(function(){
selection = i;
console.log("sel: " + selection + " i: " + i);
});
}
}
You want to take a look at JavaScript closure inside loops – simple practical example. As the answer to that question says, you can create a function to return one, or you can use inline function invocation in the for loop like so:
for(var i = 0; i < myhand.length; i++) {
$('#dd'+i).click((function(x) {
return function () {
selection = x;
console.log("sel: " + selection + " x: " + x);
}
}(i)));
}
Because the value of i is determined at the time the click handler is run. So it will always have the value of myhand.length - 1, which is the state you left i in after the for-loop.

Categories

Resources