array :
int[,] nums = new int[3,4]{
{6,7,9,8},
{4,2,1,3},
{9,7,0,4}
};
I need to print out the rows in reverse but keep the columns in same order.
Iooked all over the internet I don't even know where to start my code, all I have is a for loop that prints in reverse but when I run my code nothing shows up.
for (row = 3; row >= 0; row--)
{
for (column = 0; column < 4; column )
{
Console.Write("{0} ",nums[row,column]);
}
}
I'm definitely missing something and the only error I get is the index out of bounds.
CodePudding user response:
Please, do not use magic numbers like 3
, 4
, but actual array lengths, GetLength(...)
:
int[,] nums = new int[3, 4] {
{ 6, 7, 9, 8 },
{ 4, 2, 1, 3 },
{ 9, 7, 0, 4 },
};
for (int row = nums.GetLength(0) - 1; row >= 0; --row) {
for (int column = 0; column < nums.GetLength(1); column)
Console.Write($"{nums[row, column]} ");
if (row > 0)
Console.WriteLine();
}
CodePudding user response:
As you know indexes in an array go from 0 to upper bound so when cycling through an array you should consider that an array with 3 elements will have indexes 0, 1 and 2, but you are trying to access index 3 which does not exist.
High level languages have all kinds of safeguards to avoid this, among which is exception throwing when defective code is encoutered which is what you are experiencing.
That said, you can avoid direct indexing because it's very easy to get these off-by-one errors, you should always try to use range based loops, if that's not possible get the length of the array by code, don't use hard coded dimensions if you can avoid it. And here you can:
int[,] nums = {
{6,7,9,8},
{4,2,1,3},
{9,7,0,4}
};
for (var row = nums.GetUpperBound(0); row >= 0; row--)
{
for (var column = 0; column < nums.GetLength(1); column )
{
Console.Write("{0} ",nums[row,column]);
}
Console.WriteLine(); // line break for tiddy print
}
CodePudding user response:
This should work
for (row = 2; row >= 0; row--)
{
for (column = 0; column < 4; column )
{
Console.Write("{0} ",nums[row,column]);
}
}
CodePudding user response:
for (row = 3; row >= 0; row--)
The program is throwing OutOfRangeEception, because when you have an array[3,4], the last index of row is 2. Your program was trying to find an element with too large index number(3). Here you have working code
int[,] nums = new int[3, 4] { { 6, 7, 9, 8 }, { 4, 2, 1, 3 }, { 9, 7, 0, 4 } };
for (int **row = 2**; row >= 0; row--)
{
for (int column = 0; column < 4; column )
{
Console.Write("{0} ", nums[row,column]);
}
Console.WriteLine();
}
As you can see, changing value in for loop from 3 to 2 fixed the problem. And one important note from me - try to declare counter variables inside for - do not make it "global" if you don't need to. In bigger project it could use more memory than necessary. When it's inside for, garbage collector will destroy the variable after all loops