Dependent quadratic loops
Notes:
Linear loop:
for(var i=1; i<=n; i++){
sequence of statement(s); // n times
}
Quadratic loop:
for(var i=1; i<=n; i++){
for(var j=1; j<=n; j++){
sequence of statement(s); // n x n times
}
}
Cubic loop:
for(var i=1; i<=n; i++){
for(var j=1; j<=n; j++){
for(var k=1; k<=n; k++){
sequence of statement(s); // n x n x n times
}
}
}
Dependent quadratic loop:
Inner loop iterations depend upon the outer loop counter variable value
Syntax:
for(var i=1; i<=n; i++)
{
for(var j=1; j<=i; j++)
{
sequence of statement(s); // n (n+1) / 2 times
}
}
1 + 2 + 3 + 4 + ……. +n = n (n+1) / 2
Ex:
for(var i=1; i<=2; i++)
{
for(var j=1; j<=i; j++)
{
document.write(“Hello World <br/>”); // 2 (2+1) / 2 = 3 times
}
}
Interview Questions: