Wednesday, June 30, 2021

C# Array Dimension, LowerBound, UpperBound, Length, Size on the fly



using System;
namespace ConsoleArray
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the array size");
            string arr_size = Console.ReadLine();
            int arrSize = Convert.ToInt32(arr_size);
            int[] myArr;
            myArr = new int[arrSize];
            Console.WriteLine("\nResult:");
            for (int i = 0; i < myArr.Length; i++)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine("One-Dimensional Array has dimension=0");
            Console.WriteLine("LowerBound:{0}", myArr.GetLowerBound(0));
            Console.WriteLine("UpperBound:{0}", myArr.GetUpperBound(0));
            Console.WriteLine("Length:{0}", myArr.Length);
            Console.ReadKey();
        }
    }
}
OUTPUT
Enter the array size
8

Result:
0
1
2
3
4
5
6
7
One-Dimensional Array has dimension=0
LowerBound:0
UpperBound:7
Length:8



using System;
namespace ConsoleArray
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the array first dimension size");
            string arr_dim1 = Console.ReadLine();
            int arrDim1 = Convert.ToInt32(arr_dim1);
            Console.WriteLine("Enter the array second dimension size");
            string arr_dim2 = Console.ReadLine();
            int arrDim2 = Convert.ToInt32(arr_dim2);


            int[,] myArr;
            myArr = new int[arrDim1 , arrDim2];

            Console.WriteLine("\nResult:");
            for (int i = 0; i < myArr.GetUpperBound(0)+1; i++)
            {
                for (int j = 0; j < myArr.GetUpperBound(1)+1; j++)
                {
                    Console.WriteLine("({0},{1})={2}",i,j, i+j);
                }
            }

            Console.WriteLine("Two-Dimensional Array has dimensions =0, 1");
            Console.WriteLine("LowerBound, 1st Dim:{0}", myArr.GetLowerBound(0));
            Console.WriteLine("UpperBound, 1st Dim:{0}", myArr.GetUpperBound(0));
            Console.WriteLine("LowerBound, 2nd Dim:{0}", myArr.GetLowerBound(1));
            Console.WriteLine("UpperBound, 2nd Dim:{0}", myArr.GetUpperBound(1));
            Console.WriteLine("Length:{0}", myArr.Length);
            Console.ReadKey();
        }
    }
}
OUTPUT
Enter the array first dimension size
3
Enter the array second dimension size
4

Result:
(0,0)=0
(0,1)=1
(0,2)=2
(0,3)=3
(1,0)=1
(1,1)=2
(1,2)=3
(1,3)=4
(2,0)=2
(2,1)=3
(2,2)=4
(2,3)=5
Two-Dimensional Array has dimensions =0, 1
LowerBound, 1st Dim:0
UpperBound, 1st Dim:2
LowerBound, 2nd Dim:0
UpperBound, 2nd Dim:3
Length:12

NOTE: Dimension begins from 0, so we get UpperBound one less than the size of the dimension.

Edited on 6th July 2023

No comments:

Post a Comment

Hot Topics