For loop continue why is the resulting number 16? - javascript

Im starting to learn programming, and there is a particular part of the course that is blowing over my head, in the continue section about for loops, im asked to write the output of this code:
var sum=0;
for(i=4; i<8; i++) {
if (i == 6) {
continue;
}
sum += i;
}
document.write(sum);
and for whatever reason, it is supposed to equal 16, i just cant quite picture in my head why, thank you in advance!

Let's follow it through:
sum = 0
At the beginning of the loop, i = 4.
i < 8 is true so the loop continues (yes, this check happens at the very beginning)
Since i == 6 is false, continue doesn't happen
sum += i sets sum to 4
i++ sets i to 5;
i < 8 is true so the loop continues
i == 6 is false so continue doesn't happen
sum += i sets sum to 9
i++ sets i to 6
i < 8 is true so the loop continues
Since i == 6 is true, continue moves on to the next loop iteration, skipping the rest of the loop body
i++ sets i to 7
i == 6 is false so continue doesn't happen
sum += i sets sum to 16
i++ sets i to 8
i < 8 is false so the loop stops
Step #12 is probably the most interesting step: continue skips the rest of the loop body, moving on to the next loop iteration. More about continue on MDN.
Put it another way: The loop sets i to 4, increments i once per loop, and continues while i < 8. That means that within the loop body, i will be 4, then 5, then 6, then 7. In the loop body, sum += i adds i to sum except when i == 6 because continue skips over that part. So sum += i happens for 4, 5, and 7. Since sum starts at 0, it's 0 + 4 + 5 + 7 which is 16.

This is what happens in following loop
initially sum is 0
after first loop i(4) is added to sum
in second loop i(5) is added so sum become 9
in third loop nothing is added to sum because i=6 so continue statement will be executed before adding i to sum
last last loop i(7) is added to sum and result becomes 16.
as condition for loop is i<8 so last value added be 7

Related

Why doesn't a for loop work if the condition is to make a number bigger or equal than the number in the condition?

I've been experimenting with for loops, mostly with a condition 'less than or equal'. However, I wanted to make the condition of a for loop so that the number in the initialization is bigger than that one in the condition. When I ran the code, it didn't work. And when I added the bigger than or equal operator, it crashed; here's the code:
//loop n1
for (let i = 0; i > 4; i++) {
console.log(i);
}
//loop n2
for (let i = 0; i >= 4; i++) {
console.log(i);
//loop n3
for (let i = 0; i = 4; i++) {
console.log(i);
None of these worked, and the last one crashed. I don't get it; according to my logic, loop n3 should have stopped when "i" is equal to 4, but no, it crashed. And loop n1 should've stopped when "i" is more than 4.
Can anybody explain this to me?
Thanks
for will run while condition is true
// will exit right away, i is smaller then 4
for (let i = 0; i > 4; i++) {
console.log(i);
}
// will exit right away, i is smaller then 4
for (let i = 0; i >= 4; i++) {
console.log(i);
}
// will exit right away, i is smaller then 4
for (let i = 0; i === 4; i++) {
console.log(i);
}
The issue you're encountering is that the condition needs to resolve to "true" in order for the loop to continue. Let's run through your examples...
For the first one, you start with i is equal to zero (0), and then test for i being greater than four (4). Well, zero (0) is less than four (4). That immediately fails and the loop does not execute.
For the second one, again you start with i equal to zero (0), and your condition of i being greater than or equal to four (4) still fails.
In your third example, it's still pretty much the same as the previous two because zero (0) is not equal to four (4).
For your for loops to successfully execute, the condition statement has to return "true" for at least the first value that your iterator (in this case the variable i) is set to. If you want to try a loop that works, for the first two examples you can change the "greater than" (> / >=) to "less than" (< / <=) and then it will run. Or, if you change the value of i to be four (4) or greater than four, and change your incrementing statement from "i++" to "i--", that would also allow it to run. For your final example, something like that would be far better off being done as an if statement instead of a for loop.

While Loop Logic

I just have a question about some while loop logic.
So, when you write a loop that displays a string of numbers to a document and say that while the loop is <= (less than or equal to) say, 5, and you tell the loop to add 1 each time this is true, wouldn't that mean that: while the loop is equal to 5 that it would add one to 5 too? It doesn't, but I messed up on some code when I was practicing and noticed that when it is equal to five it does not add one, but I thought it would...
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text); // Should print `1 2 3 4 5 `.
the reason your text doesn't display a 6 isn't because i isn't incremented. It's because the text gets added onto before it's incremented.
In other words when executing on that 5th loop, the text would add on 5, and then it would increment i, and then it would check the loop again, which would no longer be valid and therefore 6 is never printed.
In memory, it adds one. It doesn't add it to the text though.
Since you're incrementing the value after assigning it and then the loop condition fails, it doesn't get to the part where you concatenate the string.
It does. Just output i and you'll see it's 6. text never gets the 6 because of when you increment i.
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text,i); // Should print `1 2 3 4 5 `.
b/c you +1 after you add i to text, all you need to do is switch the two line order.
EDIT
if you want it start with one just change your i to 0 to start with.
i = 1
console.log('2nd Loop:');
text = '';
i = 0;
while (i <= 5) {
i += 1
text += i + ' ';
}
console.log(text);

javascript making change algorithm

I'm solving this problem "Making change" in javascript:
Question:
Given an amount of money, an array of coin denominations, compute the
number of ways to make the amount of money with coins of the available
denominations.
Example:
For amount=4 (4¢) and denominations=[1,2,3] (1¢,
2¢ and 3¢), your program would output 4—the number of ways to make
4¢ with those denominations:
1¢, 1¢, 1¢, 1¢
1¢, 1¢, 2¢
1¢, 3¢
2¢, 2¢
I found a solution:
var makeChange = function(total){
var count = 0;
var coins = [1, 2, 5, 10, 20, 50, 100, 200];
var changer = function(index, value){
var currentCoin = coins[index];
if( index === 0){
if( value % currentCoin === 0){
count++;
}
return;
}
while( value >= 0 ){
changer(index-1, value);
value -= currentCoin;
}
}
changer(coins.length-1, total);
return count;
};
makeChange(200);
Problem(s):
Can someone explain to me what is going on? I tried following the code but i get lost in between the recursion.
I understand that he is taking the final coin value and he is substracting from the given total. (But why?) I'm kinda lost.
When value >= 0 in the while loop, It keeps looping around increasing the index, i couldn't understand why.
Can someone make sense out of this algorithm?
Sorry, just started learning Dynamic Programming.
Thank you,
Let's track what happens with makeChange(4):
The function changer gets defined then called for the first time.
value = 4, index = 7, coins[7] = 200
Since the variable, index is not 0, we move on to the while loop.
A second call to changer is made with index 6
Meanwhile, the first call continues the 'while'
loop but since 200 has been subtracted from 'value',
'value' is now less than 0 so the 'while' loop terminates
and this first call does nothing more.
(Keep in mind that the variable 'value' is distinct
and private to each call, so the 'while' loop only
affects the 'value' in its own function call.)
Ok, now this pattern continues with all the function calls that have index pointing to a coin larger than value until index is 1.
value = 4, index = 1, coins[1] = 2
This time more happens in the while loop:
We get the function call, 'changer(0,4)',
AND a second function call, 'changer(0,2)',
after we subtract 2 from 'value', which was 4,
AND a third function call, 'changer(0,0)',
after we subtract 2 from 'value', which was 2.
These 3 calls respectively represent:
1 + 1 + 1 + 1
2 + 1 + 1
2 + 2
Each time the line 'value -= currentCoin' is executed,
it represents the start of another set of choices for
solutions that include that coin.
4 % coins[0] = 0, meaning 4 is divisible by 1 represents 1 + 1 + 1 + 1
4 - 2 folllowed by 2 % 1 represents 2 + 1 + 1
and 4 - 2 - 2 represents 2 + 2
Total count: 3

Check lines A and count it until it changes to lines B javascript

I am sorry in advance if my title is somehow misleading and I am really sorry for my English if you wouldn't understand me, it's just not my native language!
I will try to explain as better as I can about what I try to achieve. I try to do this for past two entire days and I really need your help!
Let's say I have array with the following numbers:
2 4 6 8 10 1 3 5 2 4
I am trying to count how many even and odd numbers are here in a row, and when even/odd changes - count it again. So my answer from the array above should be:
5 (5 even numbers in a row) 3 (3 odd lines in a row) (2 even lines in a row)
Also when the counting isn't stopped it should post "<br>" instead of counted evens/odds, so it could show me results one time near to each line.
Check this example image:
I have this script which is counting, but it has a few issues: when number is even, it shows counting twice. Next, I can't figure it out how to add <br> to these lines where counting and add result only at the last line of counting. Also my counting result should be at the top, so the script should count from the end as I guess, and when I try i-- it starts the infinite loop...
var digits = ["2, 4, 6, 8, 10, 1, 3, 5, 2, 4"]
var evenCount=1, oddCount=1;
for(var i =0; i < digits.length; i++){
if(digits[i] % 2 ==0){
var oddCount=1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
}
else
var evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
Check my fiddle to see it in action:
https://jsfiddle.net/xk861vf9/8/
First, I think your code show counting twice because you misses two '{' after "for loop" and "else". After I fix the code format, I don't see it counting twice anymore.
$(document).ready(function() {
$("#sub").bind("click", function() {
$("#res").html("");
var digits = $('#content').find("span").map(function() {
return $(this).text();
});
var evenCount = 1;
var oddCount = 1;
for(var i =0; i < digits.length; i++) {
if (digits[i] % 2 ==0) {
oddCount = 1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
} else {
evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
}
});
});
Second, they are many ways to implement that. Take a look at this jsfiddle code as an example.
https://jsfiddle.net/xk861vf9/11/
The concept is to print the counted number after even/odd number changes. Then use for loop to print <br> x times (counted number - 1) so if counted number is 4, there will be 3 <br> tags followed.We also have to check if current number is the last number in array and print the counted number or else the last counted number will be skipped.
Hope this help! :)
Ps. Sorry for my bad English, not my native language too.

Looping in Eloquent Javascript

I cam across the following function in javascript:
for (var number = 0; number <= 12; number = number + 2)
show(number);
The Output is the following
0
2
4
6
8
10
12
I expected it to be
2
4
6
8
10
12
14
Why is the "0" shown first and not "2" since the "number = number + 2"comes before the "show(number);"?
This because the order of the loop is like this:
Init number.
Check the condition.
Run the loop.
Increase number by 2.
and then 2-4 again until the condition is false, if so exits the loop.
the for loop translate to something like this:
var number = 0;
while (number <= 12)
{
show(number);
number = number + 2;
}
In general for loop always work like this:
for(Init Variable; Condition ; Changing Variable)
{
//Some Code
}
translates to:
Init Variable
while (Condition )
{
//Some Code
Changing Variable
}
think of it like this :
why did you write the yellow part ?
this is the seed part which you DO WANT TO BE CONSIDERED !
so it will start with its seed value and then - will be incremented ....
0 is the initial value for the number variable in the for loop of the function:
var number = 0;
The for loop is terminated when the number variable reaches 12:
number <= 12;
Here is some more information on for loops: http://www.w3schools.com/js/js_loop_for.asp

Categories