SoFunction
Updated on 2025-03-07

Example demonstration of usage examples of various arrays in C#

This article demonstrates the basic usage of various C# arrays using examples. It mainly includes: one-dimensional array, two-dimensional array, jagged array, two arrays of different lengths, matrix arrays with 3 rows and 4 columns, etc.

The specific implementation code is as follows:

using System;
class ArrayApp
{
  public static void Main ( )
  {
    //Usage of one-dimensional array: Calculate the number of odd and even numbers in the array    ("One-dimensional array demonstration: odd and even numbers in a one-dimensional array");
    int[ ] arr1 = new int[ ] {8, 13, 36, 30, 9, 23, 47, 81 };
    int odd = 0;
    int even = 0;
    foreach ( int i in arr1 )   
    {
      if ( i % 2 == 0 )
        even ++;
      else
        odd ++;
    }
    ("There are a total of {0} Even number, {1} An odd number。", even, odd);
    //Usage of two-dimensional array: matrix of m rows and n columns    ("Two-dimensional array demonstration: 3 rows and 4 columns matrix");
    int[,] arr2 = new int[3,4] { {4,2,1,7}, {1,5,4,9}, {1,3,1,4} };
    for ( int i = 0; i < 3; i++ )
    {
      for ( int j = 0; j < 4; j++ )
      {
        (arr2[i,j] + "\t");
      }
      ( );
    }
    //Usage of serrated arrays: Two arrays with different numbers of elements    ("Serrated Array Demonstration: Two Arrays with Different Lengths");
    int[][] arr3 = new int[2][];
    arr3[0] = new int[5] {1,3,5,7,9};
    arr3[1] = new int[4] {2,4,6,8};
    //   char[][] arr3 = new char[][] { {H,e,l,l,o}, {C,s,h,a,r,p} };
    for ( int i = 0; i < ; i++)
    {
      ("The{0}The arrays are:\t",i+1);
      for ( int j = 0; j < arr3[i].Length; j++ )
      {
        (arr3[i][j]+ "\t");
      }
      ();
    }
  }
}