while loop prints 1 up and to 10, but gives back 11 - javascript

I am again working in CodeAcademy and I have continued along and now working with while loops. However, I am working a little bit in the scratchpad, and I've noticed something weird to me.
This code right below this text:
var counter = 1;
while(counter <= 10){
console.log(counter);
counter = counter + 1;
}
Gives this as a result.
Why does 11 pop up at the bottom. It shouldn't be there. Is it counting 0. Or is there some more bitter explanation to this. Would be glad to get some help, thanks :P
Result:
1
2
3
4
5
6
7
8
9
10
==> 11

This is the behavior of console. It will return the result of the last expression in some cases
var counter = 1, t="loop";
while(counter <= 10){
console.log(counter);
counter = counter + 1;
t = "loop end";
}
will give you
1
2
3
4
5
6
7
8
9
10
"loop end"

I am testing in Firefox and it is logging what the OP says.. and this is my take on it.
var counter = 1;
1 is it <= 10 yes, print add 1
2 is it <= 10 yes, print add 1
3 is it <= 10 yes, print add 1
4 is it <= 10 yes, print add 1
5 is it <= 10 yes, print add 1
6 is it <= 10 yes, print add 1
7 is it <= 10 yes, print add 1
8 is it <= 10 yes, print add 1
9 is it <= 10 yes, print add 1
10 is it <= 10 yes, print add 1
11 <-- prints it.
The while loop knows of the "counter" as it is passed in, not as it is declared 'after' or within the loop. It doesn't back reference. So it still has to go thru again.
before: 1
after: 2
before: 2
after: 3
before: 3
after: 4
before: 4
after: 5
before: 5
after: 6
before: 6
after: 7
before: 7
after: 8
before: 8
after: 9
before: 9
after: 10
before: 10
after: 11

You should do this.
var counter = 0;
while(counter < 10){
console.log(counter);
counter = counter + 1;
}
while(counter <= 10) says while counter is less than or equals to 10 it will do the loop.That's why number 11 is also printed.

The condition 'counter <= 10' allows flow to enter body of the loop when count is equal to 10. You're incrementing the count in the body so the final count will be 11.
Change the condition to 'counter < 10' and the result will be 10.
This will result in 1 - 10 and leave count as 10:
var counter = 0;
while(counter < 10){
counter = counter + 1;
console.log(counter);
}

Related

Javascript compare values in column separately and sort such columns

I have a task to find an order ('2 4 5 10 123' , the next value must be bigger than the previous one) in separate columns of nested array.
function createArray(n){
let result = [];
for (var i = 0 ; i < n; i++) {
result[i] = [];
for (var j = 0; j < n; j++) {
result[i][j] = (Math.random() * 5 | 0) + 6;
}
}
return result;
}
var n = prompt("Enter the size of array"), result = createArray(n);
I've created the function to fill this array with random values and I'd like to have:
Loop to compare values in separate columns
Sort columns, depending on how much values included in order:
For example, we have a column 2 4 8 3 7 and we're finding order here. We did and we have 3 values, creating the order -> 2 4 8. We stop it, since the number 3 break it and we start from this particular number: 3 8. Now we have an order having 3 nums included and 2 nums included, but we save the biggest one and than we compare these counter of max ordered nums in different columns and sort them in a way, that the column with the biggest counter is on the left side and column with the smallest one - on the right side;
[
1 3 5
2 7 7
6 9 1
7 2 2
8 3 1
]
^ ^ ^
5 3 2
I'll surely be glad to have some help, at least with comparing values in columns.
Thanks for attention.
Nothing helped, ask for help ;)

Efficient way to solve "CountFactors" codility question

I have been running through Codility questions and and one of the questions was to count all the possible factors of a number. I looped through the whole number got the answer but it wasn't efficient of course.
I searched for the answer and got this
function solution(N) {
var i;
var NumFactors = 0;
for(i = 1;i*i < N; i++) {
if(N%i == 0) NumFactors += 2;
}
if(i*i == N) NumFactors++;
return NumFactors
}
for anyone who hasn't tried the challenge if you run solution(24) it should return 8 as number of factors which are (1, 2, 3, 4, 6, 8,12, 24)
Since the person who wrote the code didn't leave any explanation, can someone who get what's happening kindly explain to me the i*i and the reason of incrementing NumFactors by 2.
The i*i is for checking until squareRoot(N). Because if you have a divisor for a number N then you actually have two divisor. Because the division result is another divisor. For example, in case of 24,
If you take divisor 2, you will find another divisor which is 12. Because 2 X 12 = 24. If you loop through N i.e. 1 to 24 you will get the divisors like this,
2 X 12 = 24
3 X 8 = 24
4 X 6 = 24
6 X 4 = 24
8 X 3 = 24
12 X 2 = 24
24 X 1 = 24
You see we have got redundant values after squareRoot(N). That is why for optimization we are going from 1 to squareRoot(N).
Now about increase factors by 2 is already described above. For the special case when N is a perfect square number like 36 or 49 you will face a case where 6 X 6 = 36 and 7 X 7 = 49 that is why in that case we are increasing the factor by one. Because there is actually on divisor namely 6 and 7 in our case.

how does Increment and Decrement work in Javascript

Can someone please explain why this function returns 0?
Shouldn't it return 1 since n++ = n and --n = n-1?
var x = function(n) {
return n++ - --n;
};
n++ is a post-increment, so first return the value, then will add 1 to it:
var n = 1;
console.log(n++); //shows 1, increments `n` to 2
console.log(n);//shows 2
console.log(n++); //shows 2, increments `n` to 3
--n is a pre-decrement - the value is first reduced by 1 and then return
var n = 3;
console.log(--n); //shows 2, `n` is already set to 2
console.log(n);//shows 2
console.log(--n); //shows 1, `n` is already set to 1
Here is an example to explain how this is being evaluated: When it's being evaluated:
var x = function (n) {
return n++ - --n;
};
x(5);
0. First n = 5 we go from there:
n = 5
n++ - --n
1. The post-increment has the highest precedence here, so we start with that.
2.n++ will return 5 but also change n to 6. So if we resolve that we have:
n = 6
5 - --n
3. Next in the order of precedence is the the pre-decrement operation.
4. --n will reduce n and return the new value, so:
n = 5
5 - 5
5. Finally, we solve the subtraction and get 0.
n++ - --n
if n = 10, then the value of (n++) is 10, but after that n is increased by one.
So n = 11 after evaluating (n++). if n = 11, (--n) = 10.
n++ - --n
--- ----- ---
10 n = 11 10
so the result is 0
This is a left to right evaluation and the incrementation is done after its value is used.
So lets assume the input is 10
Evaluate to 10 then increase then decrease so 10 - 10 the final expression.
Let's say n = 10
1. n++ will return the original value that n held before being incremented. And before going to the next operation n will be 11.
2. --n will decrease increased value(11) by 1, and then return the decreased value.
3. Finally, 10 - 10 is 0
Arithmetic Operations

How many images will you see when you view the following file in the modern browser

Can someone please explain why there would be 5 images. I think there should be 4 images. One before the loop and the rest after the loop execution.
My interpretation of code is as follows:
i : 0 1 2 3 4 5 6 7
c : 0 1 2 3=0 1 2 3=0 1
img: 1 2 3 2 3 3 2 3 Note: i am interpreting continue command as not to follow the code and go to next iteration therefore no another image is cloned/appended for the i=5 iteration
<!doctype html>
<html>
<head>
<script>
function do_something() {
var theBody = document.getElementsByTagName("body")[0];
var theImg = document.createElement("img");
theImg.src = "cat.png";
theBody.appendChild(theImg.cloneNode(true));
var count = 0;
for (var i = 0; i < 10; i++, count++) {
if (i == 5) continue;
if (count == 3) {
count = 0;
theBody.removeChild(theBody.lastChild);
} else {
theBody.appendChild(theImg.cloneNode(true));
}
if (i > 7) break;
}
}
</script>
</head>
<body onload="do_something()"></body>
</html>
A bit difficult to explain by me, but hope you know,
before loop you append a image (1),
and next 0 1 2 add 3 img,(4)
but at 3 remove 1 so (3),
then keep going 4 add 1 img (4)
5 just pass by
so 6 will be another 3 just remove 1 img(3)
and meet 7 add a img img(4)
but note, your last if is mean great than 7 and check at last line,
so when i become 8 still add img to body img(5)
that's why you will see 5 image at total
First image:
theBody.appendChild(theImg.cloneNode(true));
Let's analyze the loop.
for (var i = 0; i < 10; i++, count++)
It has 10 counts plus our original so 11, however:
if (i > 7) break;
Let's note that this at the end of the code - therefore it will actually run for #8
Reevaluating our potential total we have 9+1 = 10.
We can discard count #5 because of this line:
if (i == 5) continue;
So now our count is 9.
This next statement causes every 4 count to a) not print an image and b) remove an existing one.
if (count == 3)
count = 0;
theBody.removeChild(theBody.lastChild);
So 9/4 = 2. It will therefore remove 2 images and not print 2 new ones. So now we have 5

How to write a loop that prints a table of values using a tab sequence in JavaScript

What I'm trying to do here is create a table of values that displays the following as
N 10*N 100*N 1000*N 
1 10 100 1000 
2 20 200 2000 
3 30 300 3000 
4 40 400 4000 
5 50 500 5000 
6 60 600 6000 
7 70 700 7000 
8 80 800 8000 
9 90 900 9000 
10 100 1000 10000 
My code is
var index = 0;
for ( index=0; index <= 10 ;index += 1)
{
console.log(index)
}
This displays numbers from 0 to 10 down a straight line, however I'm still unclear how to use a tab sequence and to get each value to appear as "N*10". Any advice is appreciated.
If your code doesn't need to run everywhere, you can use console.table. It is available in Chrome, Firefox and Opera:
console.table([1,2,3,4,5,6,7,8,9].map(function(n){
return [n, n*10, n*100, n*1000]
}))
console.table isn't available everywhere, isn't standard (nor is any part of the console API), but it is a very useful debugging tool.
var index = 0;
for ( index=0; index <= 10 ;index += 1)
{
console.log(index + "\t" + index*10 + "\t" + index*100 + "\t" + index*1000)
}
This should work :)

Categories

Resources