Write C# Program to Convert a 2D Array into 1D Array


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. using System;
  2.  
  3. namespace Program
  4. {
  5. class twodmatrix
  6. {
  7. int p, r;
  8. int[,] a;
  9. int[] b;
  10. twodmatrix(int x, int y)
  11. {
  12. p = x;
  13. r = y;
  14. a = new int[p, r];
  15. b = new int[p * r];
  16. }
  17. public void readmatrix()
  18. {
  19. for (int i = 0; i < p; i++)
  20. {
  21. for (int j = 0; j < r; j++)
  22. {
  23. Console.Write("a[{0},{1}]=", i, j);
  24. a[i, j] = Convert.ToInt32(Console.ReadLine());
  25. }
  26. }
  27. }
  28. public void printtwodimentionalarray()
  29. {
  30. for (int i = 0; i < p; i++)
  31. {
  32. for (int j = 0; j < r; j++)
  33. {
  34. Console.Write("{0}\t", a[i, j]);
  35.  
  36. }
  37. Console.Write("\n");
  38. }
  39. }
  40. public void convert()
  41. {
  42. int k = 0;
  43. for (int i = 0; i < p; i++)
  44. {
  45. for (int j = 0; j < r; j++)
  46. {
  47. b[k++] = a[i, j];
  48. }
  49. }
  50. }
  51. public void printonedimentionalarray()
  52. {
  53. for (int i = 0; i < p * r; i++)
  54. {
  55. Console.WriteLine("{0}\t", b[i]);
  56. }
  57. }
  58.  
  59.  
  60. public static void Main(string[] args)
  61. {
  62. twodmatrix obj = new twodmatrix(2, 3);
  63. Console.WriteLine("Enter the Elements : ");
  64. obj.readmatrix();
  65. Console.WriteLine("\nGiven 2-D Array() is : ");
  66. obj.printtwodimentionalarray();
  67. obj.convert();
  68. Console.WriteLine("\nConverted 1-D Array is : ");
  69. obj.printonedimentionalarray();
  70. Console.ReadLine();
  71. }
  72. }
  73. }

Result

C# language techstudy

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.