While Loop Logic - javascript

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);

Related

Understanding While Loops and Counter - How does it work?

Understanding While Loop
I am trying to understand what exactly happens when I use the 'while loop' to execute a code multiple times.
I was solving a problem on JSHero.net and I found it confusing so I tried explaining the solution to myself in order to get a clear understanding.
Please study the question, the answer and the simple explanation and let me know if I have understood it correctly. I could have done better explaining the counter as using it inside the condition itself confused me a lot.
Thanking all the good people in advance for helping me !!
Stay Safe !!
Question
Write a function spaces that takes a natural number n and returns a string of n spaces.
Example: spaces(1) should return ' '.
Answer
function spaces(num) {
let mySpaces = '';
while (num-- > 0)
mySpaces += ' ';
return mySpaces;
};
Explanation
declare a function spaces
it has 1 parameter 'num'
declare a variable mySpaces
initialize it with an empty string
we use a while loop as we need to repeat an action multiple times
in this case we need to add blank spaces to a string
our '''empty spaces string''' will be stored in the variable mySpaces
blank spaces will be equal to the 'num' parameter, which is fed when the function 'spaces' is called
while loops have: a condition and a code (loop body)
our condition is to ensure that the code should execute as long as the num is greater than 0
our condition is (num-- > 0)
our code is: mySpaces += ''
so if our function is called with the following parameter then how would this while loop work
spaces (3)
first it will check if 3 > 0; which it is and it will execute the code
mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (1 space)
then since we have used the num as a counter (num--), the loop will reduce 1 from 3 = 2
it will check if 2 > 0; which it is and it will execute the code
mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (2 spaces)
then since we have used the num as a counter (num--), the loop will reduce 1 from 2 = 1
it will check if 1 > 0; which it is and it will execute the code
mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (3 spaces)
then since we have used the num as a counter (num--), the loop will reduce 1 from 1 = 0
it will check if 0 > 0; which it is not and it will only execute the code after the while loop
we return the mySpaces variable which will give us the final result
While construction in javascript and most popular programming language consists of these parts:
while keyword
condition inside parentheses (num-- > 0)
body (mySpaces += ' ';)
It it used to repeatedly execute statements inside the body as long as condition is true.
For example this is how would you print Hello world repeatedly 5 times (please note, for this example for loop would have been more appropriate):
i = 5;
while (i > 0) { // as long as i is above zero
console.log("Hello world"); // print 'Hello world'
i--; // decrease value of i by one
}
In this particular example execution of while loop could be described as this:
check if condition is true
if not - skip body and continue with next statement after body
if yes - execute every statement inside body once and repeat this step
It is possible based on the condition that body gets executed zero, one, or multiple times.
In your code you start with some value of num, when you enter while loop, condition is checked, it is determined, whether body should or should not be executed and then num is decreased by one (because of the -- operator). This process repeats as long as num is above zero.
Slight modification in the order:
...
<> spaces (3)
<> a variable mySpaces will be declared and initialized with an empty string literal.
<> first it will check if 3 > 0; which it is and it start the loop. The value of num has already decreased by 1 in the memory, so now num = 2.
<> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (1 space)
<> it will check if 2 > 0; which it is and it will execute the code. The value of num has again decreased by 1 in the memory, so now num = 1.
<> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (2 spaces)
<> it will check if 1 > 0; which it is and it will execute the code. The value of num has again decreased by 1 in the memory, so now num = 0.
<> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (3 spaces)
<> it will check if 0 > 0; which is false and it will not execute the code inside the while loop anymore. The value of num has again decreased by 1 in the memory, so now num = -1.
<> The last value of mySpaces which is ' ' (3 spaces) is returned from the function.
P.S. I've tried to write the answer in a way closest to how you've explained it. Hope this clears everything! Next time if you find the flow of code confusing always remember to put print statements at different places. Putting a console.log("Checkpoint 1") or printing the value of the variables in action greatly helps one to understand the changes as they happen. A more advanced way is to put breakpoints in code and debug. OnlineGDB's IDE makes a table of values for the variables and displays them at each stop.

Javascript if statement in while loop

Below you can find the code for creating random 8 numbers between 1 and 80. It puts the random numbers into the numbers array and writes into the divs. Code runs without any problem if it increments the x inside if brackets.
If I put the 'x++' outside of if brackets, after several run I found that sometimes it creates a same random number and finds inside the numbers array. Then it skips and that div comes empty.
What is the difference between incrementing x in if block and incrementing x outside if block ?
Inside the if block :
var numbers = []
var luckyNumber;
var x = 1;
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
x++;
}
}
Outside the if block :
var numbers = []
var luckyNumber;
var x = 1;
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
}
x++;
}
HTML:
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
When you put the increment outside the if condition, if there is a number already present in the numbers array, then it wont enter into the if condition and hence the div never fills up. However you move on to the next div, since you incremented the x value. If you put the x incrementation outside, the x values remains the same when the condition inside if not met, hence in the next iteration the condition may pass or its keep trying.
Execution flow
When you have increment inside if
1) Generate random number.
2) Check in is already generated, if yes skip it. // you see ? when skip no increment happens, because the increment inside the the condition.
3) Generate again and go to step 2.
When you have increment outside if
1) Generate random number.
2) Check in is already generated, if yes skip it. Increase x value to next. //** you see ? incrementing no matter you skip it or not.
3) Generate again and go to step 2.
Because in the first example you advance x only in the case if a unique random number has been generated.
In the second example you advance x regardless if the generated number was unique or not. So it could happen in this case, that out of the 8 times it tried (because that is your while condition), it generated only two unique random numbers, for example.
if you write x++ outside if it always increases by 1 ..and if you put inside if its clear that it increases when your condition is satisfied.. according to this you output may differ.
You could use do while loop for checking, if the number is already taken.
var numbers = [],
luckyNumber,
x = 1;
while (x <= 8) {
do {
luckyNumber = Math.floor(Math.random() * 80 + 1);
} while (numbers.indexOf(luckyNumber) !== -1)
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
x++;
}
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
incrementing outside, if block will execute without any condition.
But you are incrementing inside, if block will execute only in that condition is true.

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.

Adding an integer to a JavaScript variable

I have a variable declared here:
var quizScore = 0;
And I want to add a number to it each time the correctAnswer() function runs:
function correctAnswer(){
quizScore+1;
console.log ( 'correct answer selected: quizscore = ' + quizScore );
}
I added a console log for debugging. It works, so the function is being called, but it is not adding the score. Do I need to parse this to an integer? I can't work out what the +1 needs to be to work correctly.
You can go here and you will see that clicking "Lightning Bolt" for question 1 shows "correct answer" in the console, but doesn't add to the score variable.
Do it like this:
function correctAnswer(){
console.log ( 'correct answer selected: quizscore = ' + (++quizScore) );
}
You just need to assign the +1 to quizScore variable. This may be the fastest way to add 1 and display it in one line
You're adding one to whatever value is in quizScore, and doing nothing with the result.
You need quizScore = quizScore + 1.
Keep quizscore as global variable.
And secondly change the line no.1 of your correctAnswer() function to
quizScore = quizScore + 1;
You can use self-memorizing function not to pollute global environment with variables like so:
function correctAnswer() {
correctAnswer.quizScore = (correctAnswer.quizScore || 0) + 1;
console.log("QuizScore : " + correctAnswer.quizScore);
}
for (var i = 0; i < 10; i++) {
correctAnswer(); // output 1 2 3 4 5 6 7 8 9 10
}
Right now, when you do this:
quizscore+1;
You add one to it but it doesn't assign the change to the variable. One reason for this is that sometimes you may want to add a number to the variable long enough to perform an operation but you don't want it to change.
// quiz score is left alone
var nextscore = quizscore + 1
Here are the different ways to actually assign it:
// temporarily adds 1 to quizscore, then saves it to quizscore
quizscore = quizscore + 1
// adds one to quizscore after it's used in an expression
quizscore++
// adds one to quizscore before it's used in an expression
++quizscore
So if you did something like this:
var nextscore = ++quizscore + 1;
You would both increment the current score and predict the next score.
Read more: Expressions and Operators

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