# 5. your second for loop

#1

Could someone please explain to me that why add (+i) or (j<myName.length+i) in second for loop?
var text = "Anup Anup";
var myName = "Anup";
var hits = [];
for(i = 0; i < text.length; i++){
if(text[i] === 'A'){
for(j = i; j < (myName.length+i); j++){
hits.push(text[j]);
}
}
}

#2

because without myName.length+i it'll just print Anup for one time .
lets go through it...

for(i = 0; i < text.length; i++) { true
if(text[0] === 'A'){ true
for(j =0; j < (4+0); j++){ true
hits.push(text[0]);
push A
for(j =1; j < (4+0); j++){ true
hits.push(text[1]);
push n
for(j =2; j < (4+0); j++){ true
hits.push(text[2]);
push u
for(j =3; j < (4+0); j++){true
hits.push(text[3]);
push p
for(j =4; j < (4+0); j++){false

again

for(i = 1; i < text.length; i++) true
if(text[1] === 'A'){ false
for(i = 2; i < text.length; i++) true
if(text[2] === 'A'){ false
for(i = 3; i < text.length; i++) true
if(text[3] === 'A'){ false
for(i =4; i < text.length; i++) true
if(text[4] === 'A'){ false
for(i = 5; i < text.length; i++) true
if(text[5] === 'A'){ true

it's the reason

for(j =5; j < (4+5); j++){ true // **it'll be true if you add +i **

for(j =5; j < (4); j++){ false // without +i it'll be false

so if you want to print all the anup in the text then you have to add + i

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.