For Loops

For loops are control flow structures in programming that iterate over a sequence of elements or execute a block of code a predetermined number of times. They are invaluable for automating repetitive tasks and processing collections of data efficiently. For loops provide a concise and readable way to iterate over arrays, lists, and other iterable objects, enabling developers to perform operations on each element sequentially. They are widely used in various programming tasks such as data processing, generating sequences, searching and sorting algorithms, and implementing iterative algorithms.

Select Languages

Examples

C

char* names[] = {"Joe", "Alex", "Bob"};
int numItems = sizeof(names) / sizeof(names[0]);

for (int i = 0; i < numItems; i++) {
  printf("%s\n", names[i]);
}

C#

using System.Collections.Generic;

List<string> names = new List<string>();
names.Add("Joe");
names.Add("Alex");
names.Add("Bob");
  
for (int i = 0; i < names.Count; i++) {
  Console.WriteLine(names[i]);
}

C++

#include <iostream>
#include <vector>
using namespace std;

vector<string> names = {"Joe", "Alex", "Bob"};
  
for (int i = 0; i < names.size(); i++) {
  cout << names[i] << endl;
}

Go

import "fmt"

names := []string{"Joe", "Alex", "Bob"};

for i := 0; i < len(names); i++ {
  fmt.Println(names[i]);
}

Java

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
names.add("Joe");
names.add("Alex");
names.add("Bob");

for (int i = 0; i < names.size(); i++) {
  System.out.println(names.get(i) );
}

JavaScript

let names = ['Joe', 'Alex', 'Bob'];

for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}

Kotlin

val names = 
  mutableListOf("Joe", "Alex", "Bob");

for (name in names.orEmpty()) {
  println(name);
}

MatLab

names = ["Joe", "Alex", "Bob"];

for i = 1:length(names)
  fprintf(names{i} + "\n");
end

PHP

$names = array("Joe", "Alex", "Bob");

for ($i = 0; $i < sizeof($names); $i++) {
  echo $names[0];
  echo "\n";
}

Python

names = ['Joe', 'Alex', 'Bob']

for name in names:
  print(name)

R

names <- list('Joe', 'Alex', 'Bob');

for (name in names) {
  print(name);
}

Ruby

names = ['Joe', 'Alex', 'Bob'];

for name in names do
 puts name
end

Rust

let names = ["Joe", "Alex", "Bob"];

for name in names {
  println!("{}", name);
}

Scala

var names = Array("Joe", "Alex", "Bob");

for (name <- names) {
  println(name)
}

Swift

var names = ["Joe", "Alex", "Bob"];

for name in names {
    print(name);
}

TypeScript

let names:string[] = ['Joe', 'Alex', 'Bob'];

for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}

Copyright 2025. All Rights Reserved. IronCodeMan.