Looping in Eloquent Javascript - 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

Related

the less than operator in javascript (<) is working as less or equals to [duplicate]

This question already has answers here:
Generate random number between two numbers in JavaScript
(32 answers)
Closed 1 year ago.
this code is supposed to display a random character/ letter of a given name in javascript using while loops and if statements . . .
the problem that I faced is that the RandomLetterIndex is between 0 and 5 (<=5) when I want it to be between 0 and 4 (<5)
const MyName = "Ayman";
var RandomLetterIndex = Math.floor(Math.random() * 10);
while (RandomLetterIndex > MyName.length) {
RandomLetterIndex = Math.floor(Math.random() * 10);
if (RandomLetterIndex < MyName.length && RandomLetterIndex !== 5) {
break
}
}
console.log(RandomLetterIndex);
console.log(MyName.charAt(RandomLetterIndex));
If you want the random number to be less than the length of the word, instead of using while loops, you can do this
var RandomLetterIndex = Math.floor(Math.random()*MyName.length);
multiplying by length instead of 10 makes sure that the value always lies in the range [0, length-1] instead of [0, 10-1]
The problem is with the 0 based index and the length property. MyName.length will equate to 5 and thus the while loop will stop and the consoles print out.
while (RandomLetterIndex > MyName.length - 1) {
Try like this with the minus 1.
Your while loop ends when RandomLetterIndex is 5. Thats why you see a five in the console.
Also, you are breaking the loop, and therefore the while check is kind of useless.

Separating while loop output in JavaScript

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++;
}

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

for each loop run in reverse order [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Here's my code:
int myArray[]={1,2,3,4,5,6,7,8};
for(int counter=myArray.length; counter > 0;counter--){
System.out.println(myArray[counter]);
}
I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at task1.main(task1.java:14)
Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.
Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
The first index is 0 and the last index is 7 not 8
The size of the array is 8
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
The problem here is this piece of code: myArray.length. In Java, as in most other languages, Data structures are 0 based, so the last element has an index of structure.length - 1 (and the first being 0). So in your case, you should change your loop as follows:
for(int counter=myArray.length - 1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
You're starting at the wrong index. Do it like this:
for(int counter= myArray.length - 1; counter >= 0;counter--) {
The last index of an array is its length minus 1.
the counter is starting at the index of myArray.length which is actually counted from 1 instead of 0..
for(int counter=myArray.length - 1; counter > 0; counter--){
int myArray[]={1,2,3,4,5,6,7,8};
Here, given array length is 8 as the count starts from 1 but coming for the index myArray[0] = 1;
and so on.... here index count starts from 0.
So in your piece of code
for(int counter = myArray.length - 1; counter >= 0; counter--) {
goes out of the array boundary so it shows you ArrayIndexOutOfBoundsException.

Categories