var a = 0;
(++a)+(a++)+(++a);
print(a);
This prints 3. I'm assuming it only executes single increment.
var a = 0;
(++a)+(a++)+(--a);
This prints 1. What's the rule to follow here?
Thank you.
You're not assigning the outcome of your addition to anything. You do this:
(++a)+(a++)+(++a);
Which increments a 3 times. 0 + 3 = 3 so a is the value 3.
JavaScript is executed left-to-right. You can see this by seeing what happens when you use multiplication
a = 1;
++a * a; // 4
// 2 * 2 = 4
a = 1;
a * ++a; // 2
// 1 * 2 = 2
a = 1;
a++ * a ; // 2
// 1 * 2 = 2
a = 1;
a * a++; // 1
// 1 * 1 = 1
After each of these, the resulting a is 2.
Related
please someone explain this to me
function func(x, n) {
if (n == 1) {
return x;
} else {
return x * func(x, n - 1);
}
}
console.log(func(2, 4)); // 16
how do answer is 16
I could not understand more than this
when if is false it going to else
in the return section function call itself
at the first input is the same value as x, ie 2
at the second input is n - 1
when function run again the value of x remains the same as 2 and the value of n becomes 3
that's mean 3 times if is false
in the 4 times if if true and the execution loop ends and show answer in alert
i can not figure out what number is multiplied by x per run or the answer should be the same as 2
because every time the function is executed, shouldn't the value of x be equal to 2?
If you are asking about how recursion works, then I will explain you with this basic flowchart diagram.
I also edited your JS Code so it will provide you with clarification.
function func(x, n) {
if (n == 1) {
return x;
} else {
let function_returned = func(x, n - 1);
console.log(x, "*", function_returned, "=", x*function_returned)
return x * function_returned
}
}
console.log(func(2, 4));
The function performs exponentiation. So func(x, n) is calculating xn.
It uses recursion, based on the following principle:
When n is 1, then xn = x1 = x
When n > 1, then xn = x.xn-1
For the second statement we can use the function with arguments x and n-1.
For the concrete example, func(2, 4), this is what happens:
x=2, n=4, so we get in the else block and evaluate:
2 * func(2, 3)
For this nested call of func we have x=2, n=3, and again we get in the else block for that:
2 * func(2, 2)
And again we have a nested call, which evaluates to:
2 * func(2, 1)
...and this final nested call gets into the if block and evaluates to:
2
Now we need to backtrack as each nested function call returns the result to its caller:
2 is returned for func(2, 1) which turns 2 * func(2, 1) to 4
That 4 is returned for func(2, 2) which turns 2 * func(2, 2) to 8
That 8 is returned for func(2, 3) which turns 2 * func(2, 4) to 16
And that 16 is what you get in the output
It's a recursive power function. What it does is the following:
2^4 = ?
2 * 2^3 = ?
2 * 2 * 2^2 = ?
2 * 2 * 2 * (2^1) = ? // at this point we get to n == 1 and this is where result is just x which is 2 in your example. From this point we can start moving "back"
2 * 2 * (2 * 2) = ?
2 * (2 * 4) = ?
(2 * 8) = ?
16 = ? // 16 is just 16, we're done.
Your can read a bit about recursion to get a better idea on what is going on.
While I was solving a question saying "add odd numbers from 1 to 20", I coded this:
var i, sum=0;
for (i=2; i<=20; i*2){
sum=sum+i;
}
document.write(sum);
When I launched it through a browser, it did not work. However, when I fixed i*2 into i+=2, it worked.
What am I missing? Am I not able to use *(multiplier) in For Loops?
If you need to add odd numbers from 1 to 20, then you need i+=2 as the third parameter of the for and need to initialize the variable to 1 to get the correct result:
var sum = 0;
for (var i = 1; i <= 20; i += 2) {
sum += i;
}
When you have
i += 2
2 is added to i and the result is stored into i. When you tried
var i, sum=0;
for (i=2; i<=20; i*2){
sum=sum+i;
}
i*2 calculates the value which is twice as big as i, but it will not change the value of i, so this would "work" instead:
var i, sum=0;
for (i=2; i<=20; i*=2){
sum=sum+i;
}
where
i *= 2
not only calculates the value twice as big as i, but stores the result into i as well. However, even though this will run, the result will not be correct, since you are using the wrong formula.
Also, you can calculate the result without using a for:
1 + 2 + ... + n = n * (n + 1) / 2
Assuming that n is pair: and since we know that we are "missing" half the numbers and all the pair numbers are bigger exactly with 1 than the previous impair numbers, we can subtract half of the sequence
n * (n + 1) / 2 - n / 2 = (n * (n + 1) - n) / 2 = (n * (n + 1 - 1)) /
2 = n * n / 2
and now we have exactly the double value of what we need, so the final formula is:
sum = n * n / 4;
Let's make this a function
function getOddSumUpTo(limit) {
if (limit % 2) limit ++;
return limit * limit / 4;
}
and then:
var sum = getOddSumUpTo(20);
Note that we increment limit if it is odd.
The issue is that you're not updating the value of the i in the for loop.
I want add odd numbers from 1 to 20
Then you need to change the initial value of i to 1.
var i, sum = 0;
for (i = 1; i <= 20; i += 2){
sum += i;
}
document.write(sum);
Also, you can find the sum of odd numbers from 1 to 20 by using a formula.
n = 20;
console.log(n % 2 == 0 ? (n * n)/ 4 : ((n + 1) * (n + 1))/4);
You can you just have to do it simillary to what you've written about sum.
You used there i += 2 and not i + 2.
The same way just change i * 2 to i *= 2.
Here is an working example
var i, sum = 0;
for (i = 2; i <= 20; i *= 2) {
console.log(i);
sum += i;
}
document.write(sum);
But a couple of things here.
First of all you wrote
add odd numbers from 1 to 20
and in all your examples you use sum on even numbers.
Secondly, by multiplying you will not achieve your desired goal (as you can see in a snippet above in a console)
So to actually
add odd numbers from 1 to 20
you should do it like this:
var i, sum = 0;
for (i = 1; i <= 20; i += 2) {
console.log(i);
sum += i;
}
document.write(sum);
EDIT
If you want to add even numbers you still can't use multiplying.
Why? Simply because you said yourself that you want a sum of numbers.
So let's say that we start with 2.
If we multiply it by 2 it has the value 4 which is fine.
But now look what happens in the next iteration. Our variable i which has the value 4 is multiplied by 2 and now its new value is 8. So what about 6?
Next iteration multiply 8 by 2 and its new value is 16.
Do you see where this is going?
And when you use i += 2 instead of i *= 2?
So if we start with 2 and than we add 2 its new value is 4.
In next iteration we add 2 to 4 and we have 6.
And so on.
If you want to test it, here is an example with multiplying and adding.
Pay attention to console logs
var i;
console.log("Multiplying");
for (i = 2; i <= 20; i *= 2) {
console.log("i value is: " + i);
}
console.log("Adding");
for (i = 2; i <= 20; i += 2) {
console.log("i value is: " + i);
}
What you are looking is this :
let sum = 0;
for(var i = 2; i <= 20; i += 2){
sum += i;
}
document.write(sum)
Another take on this :
// set to n (what you want). Set to n + 1
var N = 21;
// The main driver code create an array from 0-(N-1) and removes all even nums
let a = Array.apply(null, {length: N}).map(Number.call, _ => +_).filter(_=>_%2)
// console.log the array
console.log(a)
You can use whatever expression in loop header, even this is a valid for loop statement for (;;) which simply runs forever (equivalent to while(true)).
Problem is that you are not updating the i counter in for (i=2; i<=20; i*2) so the i will stays the same throughout the execution of the loop.
If you change it to for (i=2; i<=20; i = i*2) or for (i=2; i<=20; i *=2) then it will work.
It is the same as if you did
let i = 1;
i * 2;
console.log(i);
i = i * 2;
console.log(i);
The first i * 2 doesn't update the i while the second one does.
You can also translate the for loop into while loop to see the error more clearly.
// wrong
let i = 1;
while(i <= 20) {
i * 2;
// do something
}
// right
let i = 1;
while(i <= 20) {
i = i * 2 // or i *= 2
// do something
}
Just a side note, if you wanted to perform sum on more types of sequences efficiently than you could use a generator based approach and write your sum function and describe each type of a sequence with a generator function.
function *generateOdd(start, end) {
for (let i = start; i <= end; i++) {
if (i % 2 === 1) { yield i; }
}
}
function *generateEven(start, end) {
for (let i = start; i <= end; i++) {
if (i % 2 === 0) { yield i; }
}
}
function sumNums(gen, start, end) {
const generator = gen(start, end);
let res = 0;
let item = generator.next();
while (!item.done) {
res += item.value;
item = generator.next();
}
return res;
}
console.log(sumNums(generateOdd, 0, 20));
console.log(sumNums(generateEven, 0, 20));
/* sum of the Odd number using loop */
function sumOfOddNumbers(n){
let sum= 0;
for(let i = 1; i <= n; i++) {
if(i % 2 !== 0){
sum = sum + i;
}
}
return sum;
}
// 567 = 1+3+5+7+9+11+13+15+17+19+21+23+25+27+29+31+33+35+37+39+41+43+45+47
let n = 47;
let sum = sumOfOddNumbers(47);
alert('sumOfOddNumbers(' + n + ') = ' + sum);
I wish to use Javascript to generate a random number between 1 and 2 inclusive.
Easy enough, I think -- something like?
Math.floor((Math.random() * 2) + 1);
But then I want to generate a second number, which if the first result is 1, is 2; and if the first result is 2, is 1.
(I hope the punctuation is clear.)
Update — random integers, I should have said (i.e. 1 or 2 only).
You can do so eloquently just by subtracting the first value from 3:
var first = Math.floor((Math.random() * 2) + 1);
var second = 3 - first;
var result = Math.floor((Math.random() * 2) + 1); // Get 1 or 2
console.log("Random was: " + result); // Test
var result2 = result === 1 ? 2 : 1; // Ternary to get 2 or 1 based on first #
console.log("Answer is: " + result2); // Test
var rest = Math.floor((Math.random() * 2) + 1);
var rest2 = rest === 1 ? 2 : 1;
console.log("Random " + rest);
console.log("Num: " + rest2);
Given that this is the only scenario your scripting will handle, you can do it with a simple if statement or a ternary like so:
if example
var firstRandomNumber = Math.floor((Math.random() * 2) + 1);
var secondRandomNumber;
if (firstRandomNumber === 1) {
secondRandomNumber = 2;
} else {
secondRandomNumber = 1;
}
Ternary example
var firstRandomNumber = Math.floor((Math.random() * 2) + 1);
var secondRandomNumber = firstRandomNumber === 2 ? 1 : 2;
So you want to generate the second number, given 1 you get 2 and given 2 you get 1.
You can use this for that:
num2 = num1 % 2 + 1
This uses the modulo operator which returns the remainder of integer division. i.e.:
1 % 2 == 1 // 1 / 2 = 0r1
2 % 2 == 0 // 2 / 2 = 1r0
I wish to use Javascript to generate a random number between 1 and 2
inclusive.
function getRandInteger(min, max) {
return Math.floor(min + (1 + max - min) * Math.random());
}
var myRandomNumb = getRandInteger(1, 2);
edit for integers only
But then I want to generate a second number, which if the first result
is 1, is 2; and if the first result is 2, is 1.
a simple if / ternary operator...
This javaScript code block is making me crazy,that how it is doing the computation behind. I try to manually do it with calculator but the results start to be different at 4. Please explain if you know how
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
if i run console.log(fac(1));
// > 1
if i run console.log(fac(2));
// > 2
if i run console.log(fac(3));
// > 6
i was thinking this is what was happening behind
(2-1) * 2 = 2,
(3-1) * 3 = 6,
until i put
(4-1) * 4 = 12.
if i run console.log(fac(4)); the output is 24 not 12
// > 24 how and why?
cheers
It is performing recursive function call to the same function.
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
fac(4);
Value of n is 4. So it should returnfac(4 - 1) * 4). Now fac(4 -1) is calculated before returning the value.
Value of n is 3. Now it will return fac(3 - 1) * 3), which replaces fac(4 - 1) in previous statement. So, it will become fac(3 - 1) * 3 * 4.
Value of n is 2. Now it will return fac(2 - 1) * 2), which replaces fac(3 - 1) in previous statement. So, it will become fac(2 - 1) * 2 * 3 * 4.
Value of n is 1. Now it will return fac(1 - 1) * 1), which replaces fac(2 - 1) in previous statement. So, it will become fac(1 - 1) * 1 * 2 * 3 * 4.
Value of n is 0. Now it will return 1, which replaces fac(1 - 1) in previous statement. So, it will become 1 * 1 * 2 * 3 * 4.
As you can see, you can avoid multiplying by 1 twice by changing your code to
function fac(n) {
if (n == 1)
return 1;
else
return fac(n - 1) * n;
}
In short,
function fac(n) {
return (n == 1) ? 1 : (fac(n - 1) * n);
}
That's a factorial. It's calculates all permutation a set with n elements has. Or simpler:
[factorial] is the product of all positive integers less than or equal to n.
Wikipedia:Factorial
It's noted as n!. For example:
1! = 1
2! = 1 * 2 = 2
3! = 1 * 2 * 3 = 6
4! = 1 * 2 * 3 * 4 = 24
What the function is doing is recursively calling itself. When you execute the function fac(4) the following happens:
At fac(4), since 4 != 0 the value returned is fac(4 -1) * 4. However, since the return function contains a reference to a function, we wait for it to return a value.
At fac(3) (i.e. fac(4-1)), since 3 != 0 the value returned is fac(3-1) * 3. However same thing happens and we wait for result of fac(3-1)/fac(2).
At fac(2) (i.e. fac(3-1)) since 2 != 0 the value returned is fac(2-1) * 2. Again, since we are calling a function we wait for its return until we proceed will calculation.
At fac(1) (i.e. fac(2-1)) since 1 != 0 the value returned is fac(1-1)* 1 and we defer for fac(1-1) to return result.
At fac(0) (i.e. fac(1-1)) since 0==0 we return value one which is neutral for multiplication.
In fac(1), fac(1-1) becomes one, so fac(1) value becomes 1*1 or 1.
In fac(2), fac(2-1) is replaced with 1 so fac(2) becomes 1*2 or 2.
In fac(3), fac(3-1) is replaced with 2, and fac(3) becomes 2*3 or 6.
In fac(4), fac(4-1) is repalced with 6 and fac(4) becomes 6*4 or 24.
In the code below, how does the code know to do something like this, if n = 8:
8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
instead of doing * 0 at the end? Does the counting variable (n, or any counting variable ever) never hit 0 when using n--?
var n = document.getElementById("selNumber").value;
var result = 1;
while(n) {
result *= n;
n--;
}
Because when n = 0, the 0 is interpreted as false and the loop is never entered.