while loop, JavaScript printing unexpected value - javascript

I have gone through this Question and Answer While loop inside while loop JavaScript
function getMaxLessThanK(n, k) {
let i = 1;
while (i < n) {
let j = i + 1;
while (j < n + 1) {
console.log(i, j)
j++
}
i++
}
}
when n = 5, what am I getting is
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
undefined
How to avoid this the last line undefined. what is the reason for it?
Can anyone help on this please?
Edit:
This is what the actual thing I am doing below.

If you're running it in a console and get an undefined like this:
This undefined indicates that your statement runs without returning a value. It's not a result of your console.log.
If you make the function return something:
function getMaxLessThanK(n, k) {
let i = 1;
while (i < n) {
let j = i + 1;
while (j < n + 1) {
console.log(i, j)
j++
}
i++
}
return 'return value';
}
Then you'll get

Related

How to store and print out a sum that's in a for loop?

The program is this: Insert a number, for example 5 and add it with all numbers below it. In this case, it would be 5+4+3+2+1=15
I have this:
var res = 0
function addUp3(num) {
for (var i = 0; i <= num; i++) {
console.log(i);
res += i;
console.log(res);
}
}
I have no clue why it prints out random numbers.
The output of this was:
0,0,1,1,2,3,3,6 (without commas)
I've tried looking for an answer online, but they all want to do it with arrays, I don't think it's neccesary to do so. Can someone open my mind a bit please.
The for loop adds i each time. 0 + 1 + 2 + ... n. The reason it's printing twice is because you have 2 console.logs.
Log 1 prints 0 (i)
Log 2 prints 0 (res + i)
Log 3 prints 1 (i)
Log 4 prints 1 (res + i)
Log 5 prints 2 (i)
Log 6 prints 3 (res + i, which here would be 1 + 2)
If you just want the final answer, have a console.log(res) after your for loop
var res = 0
function addUp3(num) {
for (var i = 0; i <= num; i++) {
res += i;
}
console.log(res)
}
I moved the final print of res out of the loop and started the loop at 1 instead of 0
var res = 0
function addUp3(num) {
for (var i = 1; i <= num; i++) {
console.log(i);
res += i;
}
console.log(`sum: ${res}`);
}
addUp3(5);

Problems in understanding javascript nested for loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I try to understand nested for loops in javascript but it's very confusing.
I have this code and I can't understand how it works:
let n = 5;
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
console.log(j);
}}
In console I have : 0
1
0
1
2
0
1
2
3
And I'm trying to figure out which loop represent each number.
Run this code:
let n = 5;
let str = '';
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++)
str += j;
console.log("Outer: "+i+" Inner: "+str);
str = '';
}
Output is:
Outer: 0 Inner:
Outer: 1 Inner: 0
Outer: 2 Inner: 01
Outer: 3 Inner: 012
Outer: 4 Inner: 0123
As you can see, in the output above, inner loop (the one with variable j) doesn't run, because if you replace the variables with numbers it would be
0 < 0 (i < 0), which isn't true.
The best way for you to understand how nested loops work is to write each step and variable values on the paper, like so:
n = 5
STEP 1:
i = 0
i < n (0 < 5) TRUE
j = 0
j < i (0 < 0) FALSE inner loop doesn't execute
OUTPUT: "Outer: 0 Inner:"
str = ''
STEP 2:
i = 1
i < n (1 < 5) TRUE
j = 0
j < i (0 < 1) TRUE
str = 0
j = 1 (j++)
j < i (1 < 1) FALSE
OUTPUT: "Outer: 1 Inner: 0"
str = ''
And so on... Keep repeating this until the argument in the outer loop is false (i < n).
You must remember, in for loop the sequence of orders executed:
for(let i = 0; i < 5; i++) {
console.log('It works');
}
let i = 0; (this executes only once)
i < 5 (if true run 3 and 4)
run the code in loop
i ++
i < 5 (if true run 6 and 7)
run the code in loop
i++
etc.

I don't get squaring loop index in prime number function

Below are my functions that sum up all prime numbers that are below a given maxNum.
I don't understand why the for loop in the isPrime function doesn't work when using j <= num instead of j ** 2 <= num.
function sumPrimes(maxNum) {
let sum = 0;
for (let i = 2; i <= maxNum; i++) {
if (isPrime(i)) {
sum += i
}
}
return sum
}
function isPrime(num) {
for (let j = 2; j <= num; j++) { // when I use j ** 2 <= num it works
if (num % j === 0) {
return false
}
}
return true
}
console.log(sumPrimes(20))
if you use j <= num, the loop will count j up to the number itself and then it would match num % j === 0 and return false.
So if num was 17, the loop would be executed with 17 <= 17 which passes and the loop body executes 17 % 17 === 0 so it always returns false, no matter what number you pass in.
you could use j < num instead of j <= num in the loop head which should also work because the number itself is never reached when using the smaller than sign.

How to perform j operations on array?

Given an array of integers, what's the most efficient way to perform j operations on the array where the value of j could be => or <= array.length?
I tried something like this...
function performJ(arr, j) {
arr.sort((a, b) => b - a);
let i = 0;
while (j !== 0) {
if (i < arr.length) {
arr[i] = Math.ceil(arr[i] / 2)
} else {
// when i reaches arr.length, reset it to continue operations j
i = 0;
arr[i] = Math.ceil(arr[i] / 2)
}
// increment i, step through arr
++i;
// decrement j as we perform operations on arr
--j;
}
return arr.reduce((a, b) => a + b);
}
That works for a lot of cases, but for some reason it seems like large inputs of arr and j cause arithmetic operations in the while loop to get way off.
Thanks!
EDIT: Edited question for clarity. I previously had a solution that worked, but it took way too long. This solution's arithmetic is off, but works much faster.
Use modulo to iterate on indicies [i % arr.length] from 0 to j:
function performJ(arr, j) {
arr.someMethod(); // ?
for (let i = 0; i < j; i++) {
arr[i % arr.length] = /* operation */
}
return arr.someMethod(); // ?
}
Why not just a for loop like this?
for(let i = 0; i <= j; i++) {
const index = i % array.length;
array[index] = doSomething();
}
if array.length is 5 but j is 3 then doSomething() will only be called on the first three elements. if array.length is 3 but j is 5 then i will reach 3 and 3 % 3 === 0 so index will loop back to the beginning. That means doSomething() will be called on all three elements once and during the second run on only the first two elements.
Is this what you want?

Nested loops var declaration

I want to print this
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
The code appears to look like this, after many guesses
var a=5;
for (var i = 1; i <= a; i++) {
var result="";
for (var j = 1; j <= a; j++) {
result +=(i+j - 1)+ " ";
}
console.log(result);
}
But I still can't quite understand why if the var result declaration is in some other place (for example outside the loops) the result is completely different.
It is not the declaration, which is hoisted for var, but the first value for each row.
var a = 5,
result;
for (var i = 1; i <= a; i++) {
result = "";
for (var j = 1; j <= a; j++) {
result += (i + j - 1) + " ";
}
console.log(result);
}
You can take the declaration of result out of the loop as in:
var a = 5, result;
for (...
...
But you must clear it in each outer loop iteration or it will print an ever increasing row of repeated patterns per iteration.
Final code is:
var a = 5, result;
for (var i = 1; i <= a; i++) {
result = ""; //Clearing happens here.
for (var j = 1; j <= a; j++) {
result += (i + j - 1) + " ";
}
console.log(result);
}

Categories