In this tutorial we will learn C# arrays by examples.

Example 1: Int Array Examples

Create a simple integer array and loop through it printing its values in the console.

Step 1: Write Code

using System;

namespace CSArrayDemo
{
    class SimpleArray
    {

        static void Main(string[] args)
        {
            int[] num =new int[4] { 101, 201, 301, 401 };
            foreach(int i in num) {
                Console.WriteLine("Element[{0}]", i);
            }

            Console.ReadKey();
        }
    }

}

Step 2: Run

Run the code. You will get the following:

Element[101]
Element[201]
Element[301]
Element[401]

Example 2: Looping through an array using for and foreach loops

This example will demonstrate to you how to loop through an array using either for and foreach loops.

Step 1: Write Code

using System;

    class ArrayExample
    {
        static void Main(string[] args)
        {
        int[] arr = new int[10];
        for(int i=0;i<arr.Length;i++)
        {
            arr[i] = i;
            Console.WriteLine(i);
        }
        Console.WriteLine("Using For Each");
        foreach (int j in arr)
        {
            Console.WriteLine(j);
        }

        }
    }

Step 2: Run

Run the code and you will get the following:

0
1
2
3
4
5
6
7
8
9
Using For Each
0
1
2
3
4
5
6
7
8
9