The foreach loop is used with arrays and collections. The foreach loop accesses arrays and collections in a unique way without using counters. A program iterates over a collection. The index of each element is not needed. Only the elements are needed. With foreach we access just the elements.
for loop uses counter while foreach can be used without counters.
Example1
The program prints array elements using foreach loop.
The program prints array elements using foreach loop.
class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
OUTPUT:
1
2
3
4
5
6
7
8
9
Example2
OUTPUT: dog cat ratclass Program{static void Main(){string[] str = { "dog", "cat", "rat" };foreach (string s in str){Console.WriteLine(s);}}}
No comments:
Post a Comment