C# example of 1 dim and 2 dim arrays

In these examples, the dimensions of the array are input by the user

///////////// Declaring 1 - dimensional arrays

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            // declaration of integer array
            int[] myArray1 = new int[5];
            int[] myArray2 = { 10, 20, 30, 40 };
            int[] myArray3 = new int[5] { 100, 200, 300, 400, 500 };
            int[] myArray4;

            myArray4 = new int[5];

            foreach(int n in myArray3)
               Console.WriteLine(n);
             
        }
    }
}

/////// Creating a dynamic One dimensional array, and taking array inputs from the user.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myArray;
            int length;
            Console.WriteLine("Enter array length: ");
            length = int.Parse(Console.ReadLine());

            myArray = new int[length];

            for (int i = 0; i < myArray.Length; i++)
                myArray[i] = Convert.ToInt32(Console.ReadLine());

            foreach (int i in myArray)
                Console.WriteLine(i);
            
            
             
        }
    }
}

////// Declaring a two dimensional array, taking dimensions as input from the user, and taking array values from user

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] twodim;
            Console.WriteLine("enter rows and cols: ");
            int rows = int.Parse(Console.ReadLine());
            int cols = int.Parse(Console.ReadLine());

            twodim = new int[rows, cols];

            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                  //  Console.WriteLine("Enter value for twodim[{0},{1}]: ", row, col);
                    Console.WriteLine("Enter value for twodim: ["+row+","+col+"]");
                    twodim[row, col] = int.Parse(Console.ReadLine());
                }
            }

            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {                   
                    Console.Write(twodim[row, col] + " ");
                }
                Console.WriteLine();
            }
             
        
        }
    }
}

===================================================================

 

 

Add a Comment

Your email address will not be published. Required fields are marked *