Nested Loops
Nested loops in programming are when one loop is placed inside another. This allows for the iteration of one or more loops within the body of another loop. Each time the outer loop executes, the inner loop completes its full iteration. Nested loops are commonly employed for tasks involving multidimensional data processing, pattern printing, or handling complex data structures. Efficient use of nested loops is essential, considering potential impacts on code readability and execution time for larger datasets.
Below is the implementation of Nested Loop in Programming:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 3; i++) {
int j = 0;
while (j < 5) {
cout << "i = " << i << " j = " << j << " ";
j++;
}
cout << endl;
}
return 0;
}
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 3; i++) {
int j = 0;
while (j < 5) {
System.out.print("i = " + i + " j = " + j
+ " ");
j++;
}
System.out.println();
}
}
}
for i in range(3):
j = 0
while j < 5:
print(f"i = {i} j = {j} ", end="")
j += 1
print()
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 3; i++)
{
int j = 0;
while (j < 5)
{
Console.Write($"i = {i} j = {j} ");
j++;
}
Console.WriteLine();
}
}
}
// Define the main function
function main() {
// Start a for loop to iterate from 0 to 2
for (let i = 0; i < 3; i++) {
// Initialize j
let j = 0;
// Start a while loop to iterate while j is less than 5
while (j < 5) {
// Print the values of i and j
console.log("i = " + i + " j = " + j + " ");
// Increment j
j++;
}
// Print a newline after each inner loop iteration
console.log();
}
}
// Call the main function
main();
Output
i = 0 j = 0 i = 0 j = 1 i = 0 j = 2 i = 0 j = 3 i = 0 j = 4 i = 1 j = 0 i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 1 j = 4 i = 2 j = 0 i = 2 j = 1 i = 2 j = 2 i = 2 j = 3 i = 2 j = 4
Loops in Programming
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They’re essential as they reduce hours of work to seconds. In this article, we will explore the basics of loops, with the different types and best practices.
Table of Content
- What are Loops in Programming?
- Types of Loops in Programming
- For loop
- While Loop
- Do-While Loop
- Nested Loops
- For Loop vs While Loop vs Do-While Loop in Programming
- Common mistakes to avoid in Programming