OneBite.Dev - Coding blog in a bite size

Loop Array In C#

Code snippet for how to Loop Array In C# with sample and detail explanation

Looping through an array is a fundamental programming concept that can be used in various situations. In this article, we will demonstrate how to use loops to iterate over an array in C# and explain the method in an uncomplicated, step-by-step manner.

Code snippet for Looping through an Array in C#

Consider the following example of a for loop iterating through an array in C#:

int[] myArray = new int[] {1, 2, 3, 4, 5};
for(int i=0; i<myArray.Length; i++)
{
    Console.WriteLine(myArray[i]);
}

In this code, we’ve declared an array myArray of integer type that contains five elements. We then execute a for loop that starts with i=0 and runs up to the length of the array. In each loop iteration, we print out the array element corresponding to the current index i.

Code Explanation for Looping through an Array in C#

Let’s break down how this code works:

  1. Declare an array: The first line int[] myArray = new int[] {1, 2, 3, 4, 5}; declares a new integer array named myArray with five elements; 1, 2, 3, 4, and 5.

  2. Set up the loop: The loop is set up with the for(int i=0; i<myArray.Length; i++) line. This means that a loop will start with i equal to 0 and will continue as long as i is less than the length of the array (i.e., the number of elements in the array). After each iteration, i is increased by 1 (i++).

  3. Execute code within the loop: Within the loop, the line Console.WriteLine(myArray[i]); is executed. This line prints out the value of the array element at index i. As i increases with each iteration, this will print out every element in the array.

That’s it! This code provides a simple, efficient way to loop through each element in an array using C#. Remember that arrays are zero-indexed in C#, so always start your loop with i=0 to ensure you include the first element.

c-sharp