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,924 questions

51,857 answers

573 users

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

1 Answer

0 votes
using System;

class Program
{
    static int[,] AddColumn(int[,] original, int[] new_col) {
        int lastRow = original.GetUpperBound(0);
        int lastColumn = original.GetUpperBound(1);
        
        int[,] new_arr2d = new int[lastRow + 1, lastColumn + 2];
        
        for (int i = 0; i <= lastRow; i++) {
            for (int j = 0; j <= lastColumn; j++) {
                new_arr2d[i, j] = original[i, j];
            }
        }
        for (int i = 0; i < new_col.Length; i++) {
            new_arr2d[i, lastColumn + 1] = new_col[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 = AddColumn(arr2d, new int[] {7, 8});
        
        PrintArray(arr2d);
    }
}




/*
run:

1 2 3 7 
3 4 6 8 

*/

 



answered Mar 14, 2023 by avibootz

Related questions

1 answer 174 views
1 answer 185 views
1 answer 77 views
77 views asked Mar 14, 2023 by avibootz
1 answer 74 views
74 views asked Mar 14, 2023 by avibootz
1 answer 138 views
138 views asked Jan 7, 2017 by avibootz
...