Types of For loop in Programming
Last Updated :
07 May, 2024
For Loop is a control flow statement that allows you to repeatedly execute a block of code based on a condition. It typically consists of an initialization, a condition, and an iteration statement.
In C, there is only one type of for loop, It consists of three main parts initialization, condition, and update.
Syntax:
for (initialization; condition; update) {
// code block to be executed
}
Example:
C
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
In C++, there are two types of for loop:
- Traditional For Loop
- Range-based For Loop
1. Traditional For Loop in C++:
Traditional For loop consists of three main parts initialization, condition, and update.
Syntax:
for (initialization; condition; update) {
// code block to be executed
}
Example:
C++
#include <iostream>
using namespace std;
int main() {
// Standard For loop
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
return 0;
}
2. Range-based For Loop in C++:
Range-based For Loop executes a for loop over a range. This type of loop is used to iterate over the values of a data structure, say array, vector, map, etc.
Syntax:
for (range_declaration : range_expression ) {
// code block to be executed
}
range_declaration: a declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction.
range_expression: any expression that represents a suitable sequence or a braced-init-list.
loop_statement: any statement, typically a compound statement, which is the body of the loop.
Example:
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
// Range-based For loop
for(int ele: arr)
cout << ele << "\n";
return 0;
}
Java provides two types of for loops:
- Traditional For loop in Java
- For-each loop in Java
1. Traditional for loop in Java
The traditional for loop in Java is used to iterate over a block of code a specific number of times. It consists of three parts Initialization, Condition and Update.
Syntax:
for (initialization; condition; update) {
// code block to be executed
}
Example:
Java
public class Main {
public static void main(String[] args) {
// Traditional for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
2. For-each loop in Java
The for-each loop, also known as the enhanced for loop. It provides a simpler way to iterate over arrays or collections in Java.
Syntax:
for (type variableName : arrayName) {
// code block to be executed
}
Example:
Java
public class Main {
public static void main(String[] args) {
// For-each loop (Enhanced for loop)
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
}
}
In Python, there is primarily one type of for loop, which is used to iterate over sequences such as lists, tuples, strings, or other iterable objects. However, Python's for loop is quite flexible and can be used in various ways:
for loop for iterating over a sequence: This is the most common use case for a for loop in Python, where it iterates over the elements of a sequence.
Example:
Python
# Iterate over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Outputapple
banana
cherry
for loop with range(): The range() function is often used with a for loop to iterate over a sequence of numbers.
Example:
Python
for i in range(5):
print(i)
C# provides two types of for loops:
- Traditional for loop
- for-each loop
1. Traditional for loop in C#:
Traditional for loop in C# is Similar to C, C++ for loop.
Syntax:
for (initialization; condition; increment)
{
// code to be executed
}
Example:
C#
using System;
class Program
{
static void Main()
{
// Traditional For Loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
}
}
2. For-each Loop in C#:
The foreach loop in C# is used for iterating over elements in arrays and collections. It simplifies the process of iterating over such structures compared to the traditional for loop.
Example:
C#
using System;
class Program
{
static void Main()
{
// Foreach Loop
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
In JavaScript, there are three types of for loops:
- Traditional for loop
- for...in loop
- for...of loop
1. Traditional for loop in JavaScript:
Traditional for loop is used to iterate over a block of code a fixed number of times. It's particularly useful when you know how many times you want to loop beforehand.
Syntax:
for (initialization; condition; increment/decrement) {
// code block to be executed
}
Example:
JavaScript
for (let i = 0; i < 5; i++) {
console.log(i);
}
2. for...in loop in JavaScript:
The for...in loop is used to iterate over the properties of an object. It enumerates the properties of an object in arbitrary order.
Syntax:
for (variable in object) {
// code block to be executed
}
Example:
JavaScript
const person = { name: 'Sandeep', age: 30, city: 'Noida' };
for (const key in person) {
console.log(key + ': ' + person[key]);
}
Outputname: Sandeep
age: 30
city: Noida
3. for...of loop in JavaScript:
The for...of loop in JavaScript is used to iterate over the values of an iterable object, such as an array, string, map, set.
Syntax:
for (variable of iterable) {
// code block to be executed
}
Example:
JavaScript
const countries = ['India', 'China', 'Japan'];
for (const country of countries) {
console.log(country);
}
There are many types of For loop in different languages but all of serve the same purpose, that is to execute a block of code repeatedly. These are some of the common variations of for loops, each serving different purposes depending on the specific requirements of the program.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read