Types of For Loops
For loops come in various forms, each suited for different use cases and scenarios. Here are the common types of for loops:
1. Basic For Loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
The basic for loop is the most common type, used for iterating over a range of values or executing a block of code a fixed number of times. It consists of an initialization, condition, and increment (or decrement) statement.
2. For Each Loop:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
The for each loop (or enhanced for loop) is used for iterating over elements in a collection, such as arrays, lists, or sets. It simplifies the syntax of iterating over collections and does not require explicit indexing.
3. For Loop with Iterator:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Some programming languages, such as Python and JavaScript, allow for loops to iterate over iterators or generators. This allows for more flexible iteration over custom data structures or sequences.
4. For Loop with Multiple Variables:
for (int i = 0, j = 10; i < 5 && j > 0; i++, j--) {
System.out.println("i: " + i + ", j: " + j);
}
In languages like C, C++, and Java, it’s possible to have multiple loop control variables in a for loop. This can be useful for nested loops or iterating over multi-dimensional arrays.
5. Infinite For Loop:
for (;;) {
// Infinite loop
}
An infinite for loop has no termination condition, causing it to iterate indefinitely. It can be useful for tasks like event handling or continuously running programs.
6. For Loop with Step/Stride:
for i in range(0, 10, 2):
print(i) # Output: 0, 2, 4, 6, 8
Some languages support specifying a step or stride value in the for loop declaration. This allows you to control the increment or decrement of the loop control variable.
These are some of the common types of for loops found in various programming languages, each offering unique features and functionalities to cater to different programming needs.
For loop in Programming
For loop is one of the most widely used loops in Programming and is used to execute a set of statements repetitively. We can use for loop to iterate over a sequence of elements, perform a set of tasks a fixed number of times. In this article, we will learn about the basics of For loop, its syntax along with its usage in different programming languages.
Table of Content
- What is For Loop?
- For Loop Syntax
- How does For Loop work?
- For Loop in different programming languages
- For Loop in C
- For Loop in C++
- For Loop in Java
- For Loop in C#
- For Loop in Python
- For Loop in JavaScript
- For Loop in PHP
- For Loop Use Cases
- Types of For Loops
- For Loop vs other loops