How do you loop through a C# array?


To loop through an array in C#, use any of the loops. These loops have starting and ending value set that allows you to set or check value through iterations.

C# has while, do…while, for and foreach loops to loop through an array.

Let us see an example of for loop in C# −

Example

 Live Demo

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10];
         int i,j;

         for ( i = 0; i < 10; i++ ) {
            n[ i ] = i + 10;
         }

         for (j = 0; j < 10; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

Now let us see how the above works to loop through the array.

An array of 10 integers −

int [] n = new int[10];

Now, initialize elements of the above declared array −

for ( i = 0; i < 10; i++ ) {
   n[ i ] = i + 10;
}

Above the loop iterates from i=0 to i = 10 and after every iteration the value of i increments −

i++;

On every iteration until i = 10, the value is added to the array starting with element 1 as 10 −

n[ i ] = i + 10;

Output

Element[0] = 10
Element[1] = 11
Element[2] = 12
Element[3] = 13
Element[4] = 14
Element[5] = 15
Element[6] = 16
Element[7] = 17
Element[8] = 18
Element[9] = 19

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements