Exploring Time Complexity of Kruskal’s Algorithm in Python
This article is a complementary resource to the DSA with Python course.
This article is a complementary resource to the DSA with Python course.
A nested loop is a loop inside another loop. This is useful for working with multi-dimensional structures, grids, and patterns.
Imagine you have two lists: one for car attributes and one for car brands. We can use nested loops to print all possible combinations.
// List of car attributes
let attributes = ["Electric", "Fast"];
let cars = ["Tesla", "Porsche"];
for (let attribute of attributes) {
for (let car of cars) {
console.log(attribute, car);
}
}
Output:
Electric Tesla Electric Porsche Fast Tesla Fast Porsche
attributes
array. It first picks "Electric", then "Fast".cars
list.Let’s say you want to print a square pattern like this:
* * * * * * * * *
for (let i = 0; i < 3; i++) {
let row = "";
for (let j = 0; j < 3; j++) {
row += "* ";
}
console.log(row);
}
Let’s say you want to print a right-angled triangle pattern like this:
* * * * * * * * * * * * * * *
let height = 5;
for (let i = 1; i <= height; i++) {
let row = "";
for (let j = 0; j < i; j++) {
row += "* ";
}
console.log(row);
}
Now, let’s print an inverted right-angled triangle:
* * * * * * * * * * * * * * *
let height = 5;
for (let i = height; i > 0; i--) {
let row = "";
for (let j = 0; j < i; j++) {
row += "* ";
}
console.log(row);
}
A hollow square has stars only on the borders, with spaces inside:
* * * * * * * * * * * * * * * *
let size = 5;
for (let i = 0; i < size; i++) {
let row = "";
for (let j = 0; j < size; j++) {
if (i === 0 || i === size - 1 || j === 0 || j === size - 1) {
row += "* ";
} else {
row += " ";
}
}
console.log(row);
}