Loops

Sh Raj - Mar 31 - - Dev Community

Exploring the World of Loops: A Guide to All Types with Examples

In the realm of programming, loops are fundamental constructs that allow for the repetition of tasks. They provide efficiency by executing a block of code multiple times until a specified condition is met. There are several types of loops, each suited for different scenarios and requirements. Let's delve into the world of loops, exploring their types with examples in various programming languages.

1. For Loop

The for loop is widely used when the number of iterations is known beforehand.

Example (Python):

# Print numbers from 1 to 5
for i in range(1, 6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

2. While Loop

The while loop continues to execute as long as the specified condition remains true.

Example (Java):

// Print numbers from 1 to 5
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

3. Do-While Loop

Similar to the while loop, but it always executes the block of code at least once before checking the condition.

Example (C++):

// Print numbers from 1 to 5
int i = 1;
do {
    cout << i << endl;
    i++;
} while (i <= 5);
Enter fullscreen mode Exit fullscreen mode

4. For Each Loop (or Enhanced For Loop)

This loop is used for iterating over arrays or collections.

Example (Java):

// Print elements of an array
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
Enter fullscreen mode Exit fullscreen mode

5. Nested Loops

Loops within loops, allowing for more complex iterations.

Example (Python):

# Multiplication Table
for i in range(1, 6):
    for j in range(1, 11):
        print(i * j, end="\t")
    print()
Enter fullscreen mode Exit fullscreen mode

6. Infinite Loop

A loop that runs indefinitely until a break condition is encountered.

Example (JavaScript):

// Infinite loop, press Ctrl+C to stop
while (true) {
    console.log("This is an infinite loop!");
}
Enter fullscreen mode Exit fullscreen mode

7. Loop Control Statements

These statements allow for fine-tuning the behavior of loops.

Example (C):

// Print numbers from 1 to 10, skipping 5
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        continue;  // Skip 5
    }
    printf("%d\n", i);
}
Enter fullscreen mode Exit fullscreen mode

8. Loop with Array/Collection Manipulation

Loops are often used for array manipulation or processing collections.

Example (JavaScript):

// Sum of Array Elements
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}
console.log("Sum:", sum);
Enter fullscreen mode Exit fullscreen mode

9. Recursion

Although not a traditional loop, recursion can achieve looping behavior through self-referencing functions.

Example (Python):

# Factorial using recursion
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

result = factorial(5)
print("Factorial of 5:", result)
Enter fullscreen mode Exit fullscreen mode

10. Looping through Objects

In languages with object-oriented features, loops can iterate through object properties.

Example (JavaScript):

// Looping through object properties
const person = {
    name: 'John',
    age: 30,
    gender: 'male'
};

for (const property in person) {
    console.log(`${property}: ${person[property]}`);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Loops are powerful tools in programming, offering flexibility and efficiency in handling repetitive tasks. Understanding the various types of loops and when to use them is crucial for writing clean, efficient code. Whether it's iterating through arrays, handling collections, or executing tasks repeatedly, loops are a cornerstone of programming logic.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .