for loop and array

We can use for loop the iterate each element in an array.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = new int[10];

        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = i;
        }

        for (int i = 0; i < intArray.Length; i++)
        {
            Console.WriteLine(intArray[i]);
        }

    }
}
  

The output:


0
1
2
3
4
5
6
7
8
9

The length property of the array stores the element count.

Using foreach with Arrays

In C# we can use foreach loop with array.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = new int[10];

        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = i;
        }

        foreach (int i in intArray)
        {
            Console.WriteLine(i);
        }

    }
}
  

The output:


0
1
2
3
4
5
6
7
8
9

With multidimensional arrays, you can use the same method to iterate through the elements:


class MainClass
{
    static void Main()
    {
        int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
        foreach (int i in numbers2D)
        {
            System.Console.Write("{0} ", i);
        }

    }
}

The output:


9 99 3 33 5 55
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.