How to iterate efficiently through an array of integers of unknown size in C#


To iterate efficiently through an array of integers of unknown size in C# is easy. Let’s see how.

Firstly, set an array, but do not set the size −

int[] arr = new int[] { 5, 7, 2, 4, 1 };

Now, get the length and iterate through an array using for loop −

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

Let us see the complete example −

Example

 Live Demo

using System;

public class Program {
   public static void Main() {
      int[] arr = new int[] {
         5,
         7,
         2,
         4,
         1
      };

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

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

Output

Length:5
5
7
2
4
1

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements