Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to design nested loop if the limit is not multiple of parent and child limits, without using break

I have a code like below;

let total = 15;
let batch = 5;
let batchRuns = 3;

for (let i = 0; i < batchRuns; i++) {
    for(let j=0;j<batch;j++){
        console.log("hello");
    }
    console.log("-------------");
}

Now, this will print hello 15 times since 5×3=15. What if I want to print hello 14 times or 13 times, by keeping batch like 5+5+4 or 5+5+3. What I mean is, I want to print dashes after every 5 hellos and in the last iteration if it is below 5, I want to print line after that as well.

let me show the expected outputs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Case 1

total = 10;

hello
hello
hello
hello
hello
-------------
hello
hello
hello
hello
hello
-------------

Case 2

total = 12;

hello
hello
hello
hello
hello
-------------
hello
hello
hello
hello
hello
-------------
hello
hello
-------------

>Solution :

For the last batchRuns, calculate the batch and add dashes to output.

let total = 12;
let batch = 5;
let batchRuns = 3;

for (let i = 0; i < batchRuns; i++) {
  let currentBatch = i == batchRuns - 1 ? total % batch : batch;
  for (let j = 0; j < currentBatch; j++) {
    console.log("hello");
  }
  console.log("-------------");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading