In this source code example, we will demonstrate how to iterate over an Array using for loop and foreach loop in C#.
C# String Array Iteration Example
Below C# program iterates over a String Array using for loop and foreach loop:
using System;
public class ArrayDemo
{
public static void Main(string[] args)
{
string[] fruits = { "Banana", "Mango", "Apple", "Watermelon" };
Console.WriteLine("************ Array Interation using noramal for loop *************");
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
Console.WriteLine("************ Array Interation using foreach loop *************");
foreach (string i in fruits)
{
Console.WriteLine(i);
}
}
}
Output:
************ Array Interation using noramal for loop *************
Banana
Mango
Apple
Watermelon
************ Array Interation using foreach loop *************
Banana
Mango
Apple
Watermelon
C# Integer Array Iteration Example
Below C# program iterates over an Integer Array using for loop and foreach loop:
using System;
public class ArrayDemo
{
public static void Main(string[] args)
{
int[] array = new int[] { 2, 4, 5, 6, 7, 3, 2 };
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
foreach (int i in array)
{
Console.WriteLine(i);
}
}
}
Output:
2
4
5
6
7
3
2
2
4
5
6
7
3
2
Comments
Post a Comment