Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to add a row to 2D array in C#

1 Answer

0 votes
using System;

class Program
{
    static int[,] AddRow(int[,] arr, int[] new_row) {
        int lastRow = arr.GetUpperBound(0);
        int lastColumn = arr.GetUpperBound(1);

        int[,] new_arr2d = new int[lastRow + 2, lastColumn + 1];
        
        for (int i = 0; i <= lastRow; i++) {
            for (int j = 0; j <= lastColumn; j++) {
                new_arr2d[i, j] = arr[i, j];
            }
        }
        for (int i = 0; i < new_row.Length; i++) {
            new_arr2d[lastRow + 1, i] = new_row[i];
        }
        
        return new_arr2d;
    }
    static void PrintArray(int[,] array) {
        for (int i = 0; i <= array.GetUpperBound(0); i++) {
            for (int j = 0; j <= array.GetUpperBound(1); j++) {
                Console.Write(array[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
    static void Main() {
        int[,] arr2d = { {1, 2, 3}, {3, 4, 6} };
  
        arr2d = AddRow(arr2d, new int[] {7, 8, 9});
        
        PrintArray(arr2d);
    }
}




/*
run:

1 2 3 
3 4 6 
7 8 9 

*/

 



answered Mar 14, 2023 by avibootz

Related questions

1 answer 174 views
1 answer 139 views
139 views asked Jan 7, 2017 by avibootz
1 answer 123 views
123 views asked Mar 14, 2023 by avibootz
1 answer 169 views
1 answer 86 views
86 views asked Mar 14, 2023 by avibootz
...