Print Array using loop

Contents

Output

3
1
2

Code examples

C

#include <stdio.h>
int main() {
  int array[] = {3, 1, 2};
  for(unsigned int i = 0;i<sizeof(array)/sizeof(array[0]); i++) {
    printf("%i\n", array[i]);
  }
}

C++

#include <iostream>
using namespace std;
int main() {
  int array[] = {3, 1, 2};
  for(unsigned int i = 0;i<sizeof(array)/sizeof(array[0]); i++) {
    cout << array[i] << endl;
  }
}

C#

using System;
public class ArrayPrinter {
  public static void Main() {
    int[] array = {3, 1, 2};
    foreach (int num in array) {
      System.Console.Write("{0}\n", num);
    }
  }
}

Go

package main
import "fmt"
func main() {
  array := [...]int{3, 1, 2}
  for _, num := range array {
    fmt.Println(num)
  }
}

Java

public class ArrayPrinter {
  public static void main(String[] args) {
    int[] array = {3, 1, 2};
    for(int i = 0;i < array.length;i++) {
      System.out.println(array[i]);
    }
  }
}

JavaScript

let array = [3, 1, 2]
for(const i in array) {
  console.log(array[i]);
}

Perl

my @array = (3, 1, 2);
foreach $num (@array) {
  print $num."\n";
}

PHP

<?php
$array = [3, 1, 2];
foreach ($array as $num) {
  print $num."\n";
}

Python

array = [3, 1, 2]
for num in array:
  print(str(num))

Ruby

array = [3, 1, 2]
for num in array
  puts(num.to_s)
end

Rust

fn main() {
  let array: [i32; 3] = [3, 1, 2];
  for num in array.iter() {
    println!("{}", num);
  }
}

Shell

#!/bin/sh
array=(3 1 2)
for i in ${array[@]}
do
  echo ${i};
done