Iterate Over An Array In C#
Code snippet for how to Iterate Over An Array In C# with sample and detail explanation
C# is a robust programming language that offers various methods to carry out different tasks effectively, and one such task is iterating over an array. In this article, we will focus on how we can iterate over an array in C#.
Code snippet for array iteration
Here is a simple code snippet that demonstrates how to iterate over an array in C#:
using System;
class Program {
static void Main() {
int[] numbers = {1, 2, 3, 4, 5};
for(int i = 0; i < numbers.Length; i++) {
Console.WriteLine(numbers[i]);
}
}
}
With this code, you can iterate over any integer array in C# and print each element in the console application.
Code Explanation for array iteration
Let’s break down the code and explain each component of it:
-
using System;
- This is a using directive which allows the use of types in a namespace so that you don’t have to qualify the use of a type in that namespace. For our purposes, we need access to the System namespace for the Console class. -
class Program
&static void Main()
- These are the main entry points of any C# application. The main method inside the Program class gets executed when we run our program. -
int[] numbers = {1, 2, 3, 4, 5};
- Here, we are initializing an array of integers called ‘numbers’. This array contains 5 elements: 1, 2, 3, 4, and 5. -
for(int i = 0; i < numbers.Length; i++)
- This is a for loop, which is an iterative statement that allows you to perform a specified set of statements for a definite number of times. Here it will iterate through each and every element in the array.numbers.Length
returns the total number of elements in the numbers array. -
Console.WriteLine(numbers[i]);
- This line of code prints the i-th element of the numbers array on the console. Since our for loop goes from 0 to the length of numbers array, it will print every element in the numbers array.
By following these steps, we have successfully iterated over an array in C#. This method can be applied to arrays of any type, not just integers, providing a flexible solution for a variety of programming problems.