Wednesday, November 29, 2017

JAGGED ARRAYS IN C#

Jagged Arrays in C#

In this post, we will learn about Jagged Arrays in C# with an example.
Description

A Jagged array is an array of arrays. Jagged Array is also called "array of arrays" because its elements are arrays. The element size of a jagged array can be different. 

Types of Arrays in C#

Arrays can be divided into the following three categories.

    Single-dimensional arrays
    Multidimensional arrays or rectangular arrays
    Jagged arrays

Declaration of Jagged Array

Declare jagged array that has two elements.

    int[][] _RollNumber = new int[2][];

Initialization of Jagged Array

Write the below lines to initialize a Jagged Array. The size of the elements can be different.

_RollNumber[0] = new int[2];    
_RollNumberr[1] = new int[3]; 

Now, create a  in Visual Studio and write the below lines of code in it.

    using System;    
    using System.Collections;    
    using System.Collections.Generic;    
    namespace ConsoleDemo    
    {    
        class Program    
        {    
            static void Main(string[] args)    
            {    
                // Jagged Array Example    
                int[][] _JaggedArrayExample = new int[2][];// Declare jagged array      
                _JaggedArrayExample[0] = new int[] { 11, 21, 31, 41 };// Initialize the array with value           
                _JaggedArrayExample[1] = new int[] { 42, 52, 62, 72, 83, 93 };    
                // Raed and print array elements      
                for (int i = 0; i < __JaggedArrayExample.Length; i++)    
                {    
                    for (int j = 0; j < __JaggedArrayExample[i].Length; j++)    
                    {    
                        System.Console.Write(__JaggedArrayExample[i][j] + " ");    
                    }    
                    System.Console.WriteLine();    
                }    
                Console.ReadKey();    
            }    
        }        
    }   

Output

11 21 31 41
42 52 62 72 83 93

No comments:

Post a Comment