How to create, fill, and print a 2D array at runtime in C#

1 Answer

0 votes
using System;

class Program
{
    static void Main()
    {
        int rows = 3, cols = 5;

        // Create and fill the array with random numbers
        int[,] array = CreateRandom2DArray(rows, cols);

        // Print the array
        Print2DArray(array);
    }

    // ---------------------------------------------------------
    // Creates a 2D array and fills it with random integers
    // ---------------------------------------------------------
    static int[,] CreateRandom2DArray(int rows, int cols) {
        // Creates a 2D array
        int[,] arr = new int[rows, cols];
        Random rnd = new Random();

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                arr[i, j] = rnd.Next(1, 100); // random 1–99
            }
        }

        return arr;
    }

    // ---------------------------------------------------------
    // Prints a 2D array in matrix form
    // ---------------------------------------------------------
    static void Print2DArray(int[,] arr) {
        Console.WriteLine("2D array:");

        int rows = arr.GetLength(0);
        int cols = arr.GetLength(1);

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                Console.Write(arr[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}



/*
run:

2D array:
7 29 26 73 70 
81 90 89 99 96 
4 76 77 95 31 

*/

 



answered 3 days ago by avibootz
...