How to loop through all the elements of an array in C#?


Firstly, set an array and initialize it −

int[] arr = new int[] {34, 56, 12};

To loop through all the elements of an array −

for (int i = 0; i < arr.Length; i++) {
   Console.WriteLine(arr[i]);
}

Let us see the complete code −

Example

using System;
public class Program {
   public static void Main() {
      int[] arr = new int[] {34, 56, 12};

      // Length
      Console.WriteLine("Length:" + arr.Length);

      for (int i = 0; i< arr.Length; i++) {
         Console.WriteLine(arr[i]);
      }
   }
}

Updated on: 22-Jun-2020

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements