what is this 2d array doing i dont understand? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

what is this 2d array doing i dont understand?

class Program { public static void Main(string[] args) { string plainText="computer science rocks"; plainText = plainText.ToUpper(); int stringIndex = 0; //declare and dmension 2d array string[,] matrix = new string [4,11]; for (int col = 0; col < 4;col++) for(int row = 0 ;row<11;row++) if(stringIndex<plainText.Length) { matrix[col,row]=plainText.Substring(stringIndex,1); stringIndex++; } else break; // Display plain text msg in the matrix format for (int col = 0;col<4;col++){ for (int row =0;row<11;row++) Console.Write(matrix[col,row]); Console.WriteLine(); } //genarate and display coded msg string codedtext = ""; for(int row = 0; row<11;row++) for (int col=0;col<4;col++) codedtext+=matrix[col,row]; Console.WriteLine(codedtext); output: CIOEMNPCUET ERRO CSKCS

2nd Jan 2017, 7:33 PM
sakamoto448
sakamoto448 - avatar
1 Answer
0
that 2D array will hold the characters to get from plainText.Substring(stringIndex,1); so after running your first nested loop: for (int col = 0; col < 4;col++) for(int row = 0 ;row<11;row++) if(stringIndex<plainText.Length) { matrix[col,row]=plainText.Substring(stringIndex,1); stringIndex++; } else break; that 2D Array will have this value: 0 1 2 3 4 5 6 7 8 9 10 (row) 0 C O M P U T E R S C 1 I E N C E R O C K S 2 3 (col) so, after running this code: //genarate and display coded msg string codedtext = ""; for(int row = 0; row<11;row++) for (int col=0;col<4;col++) codedtext+=matrix[col,row]; Console.WriteLine(codedtext); the fetching of data now is from [col,row] and not [row, col] meaning, form (col0,row0) to (col0,row1) and so on. that is why, the result is: CIEOMNPCUET ERRO CSKCS NOTE: Actually, your variable names are busted. "row" are the horizontal members. and the "cols" are the vertical ones which you have mistakenly interchanged in your example. and that made the code more difficult to analyze.
3rd Jan 2017, 6:38 PM
Erwin Mesias
Erwin Mesias - avatar