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.
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();
}
Fiddle
As you know indexes in an array go from 0 to upper bound so when cycling through you should consider that for an array with 3 elements you will have indexes 0, 1 and 2, you are trying to access index 3 which does not exist.
High level languages have safeguards to avoid this, here an out of range type exception is thrown to let you know you are accessing memory that does not belong to the array.
You should 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 unless you have to. Here you can use member methods to figure out the bounds of the array:
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
}
This should work
for (row = 2; row >= 0; row--)
{
for (column = 0; column < 4; column++)
{
Console.Write("{0} ",nums[row,column]);
}
}
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
Related
Hi i have been trying to use a for loop to print out 7, 6, 5, 4, 3, 2, 1
int[] numbers = new int[7];
for (int i = 7; i < numbers.Length; i--)
{
numbers[i] = i - 1;
Console.WriteLine(numbers[i]);
}
Also been trying to use a while look to print out 1, 2, 3, 4, 5, 6, 7
int[] numbers2 = new int[7];
int j = 1;
while (j > numbers2.Length)
{
Console.WriteLine(array[j]);
j++;
}
Somebody that can point me in the right direction?
Try this:
int[] numbers = new int[7];
for (int i = 7; i > 0; i--)
{
numbers[i - 1] = i;
Console.WriteLine(numbers[i - 1]);
}
Since you are going down you must also modify your loop condition to stop when i gets too low, 0 in this case.
You can also iterate over reversed range:
var range = Enumerable.Range(1, 7).Reverse();
foreach (var number in range)
{
Console.WriteLine(number);
}
Or using while:
var currentNumber = 7;
while (currentNumber > 0)
{
Console.WriteLine(currentNumber--);
}
Of course with using break points and trace your code step by step, you can find the misbehaved parts of your code easily.
In this way you can learn new things instead of solving just your problems.
I think the below link will help you:
https://learn.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019
I have this loop:
for (int i = 1; i < 10; i++)
But instead I would like to have i for just numbers 1,2,4,5 and 7 and I will hardcode this.
Is there a way I can do this with something like an array?
You could use an array to give the numbers you want like this
int[] loop = new int[] {1,2,4,5,7};
foreach(int i in loop)
Console.WriteLine(i);
Or do it inline which is not as clean when the list of values grows in my opinion
foreach(int i in new int[] {1,2,4,5,7})
Console.WriteLine(i);
foreach (int i in new[] { 1, 2, 4, 5, 7 })
{
}
Basically the answers here are correct, just because you asked explicitly for a for instead of a foreach loop:
int[] loop = new int[] { 1, 2, 4, 5, 7 };
for (int i = 0; i< loop.Length; i++)
{
Console.WriteLine(loop[i]);
}
https://dotnetfiddle.net/c5yjPe
If you want particularly for loop then go with this :
var list = new List<int>() { 1, 2, 4, 5, 7 };
for (int i = 0; i < list.Count; i++) // Loop through List with for
{
Console.WriteLine(list[i]);
}
Obviously the right answer for the general case is to use foreach or an indexed lookup as shown in the other answers, but just for completeness' sake:
You can use any statement within a for expression, including conditionals. With that in mind, it is easy to build a conditional increment or even an exhaustive conditional (state machine?) for a required set:
for (int i = 1; i <= 7; i += (i == 5 || i == 2) ? 2 : 1)
{
Console.Write(i);
}
// Output: 12457
for (int i = 1; i > 0; i = i switch {1=>2, 2=>4, 4=>5, 5=>7, 7=>-1})
{
Console.Write(i);
}
// Output: 12457
Or even something really silly like a self indexing lookup:
for (int i = 1; i > 0; i = new []{0,2,4,0,5,7,0,-1}[i])
{
Console.Write(i);
}
// Output: 12457
I'm trying to move every int in array one "cell" (position) backwards (and take the first int to the last position) in a for loop. (example: if i have array of 5,6,9 the result will be 6,9,5).
Here is my code:
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length-1; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length - 1; i++)
{
Console.WriteLine(arr[i]);
}
Instead of getting
2,3,4,5,6,1
I'm getting
2,3,4,5,5.
Why is my code not working? What is the right way to do such process?
This code does what you need. Sort the array.
int[] arr = { 1, 2, 3, 4, 5, 6 };
//int[] arr = { 5, 6, 9 };
//string[] arr = { "A", "B", "C" };
var result = Enumerable.Range(1, arr.Length).Select(i => arr[i % arr.Length]).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Input data and Results:
//Input: { 1, 2, 3, 4, 5, 6 };
//Result: 2,3,4,5,6,1
//Input: { 5, 6, 9 };
//Result: 6,9,5
//Input: { "A", "B", "C" };
//Result: B,C,A
Remove the -1 :
for (int i=1; i < arr.Length-1; i++)
in both loops and let the loops run until the end. The condition should be i < arr.Length You never reach the last position.
Although you use arr[arr.Length - 1] to Index the last element, it is different with the loop. If you take a closer look at the finishing condition it says: < that means that i will never get the value of Length - 1 the loop will end one iteration before that. Another way to fix your code would be to change the condition and let i run until it gets this value. You can achieve it by: i <= arr.Length - 1. The little difference should also do the trick. This time the loop will end exactly after I has reached the value of the index of the last element
All you need to do is remove the - 1 from your for loop condition, as it is not iterating over all the elements in your array.
If iterating over an array of 6 elements, the indices are from 0 -> 5. So, for your example, you want your loop to go from index 1 to 5 (what you had been doing is iterating over indices 1-4 (since you were subtracting by 1).
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
This is my code:
I am trying to get the maximum per line, everything is going ok until the last row. It shows me 8, but should be 4.
int[,] vek = new int[,] { { 2, 5 }, { 4, 5 }, { 8, 5 }, { 4, 2 } };
int sumL=0;
double media = 0;
int maxL = 0;
maxL = vek [0,0];
Console.WriteLine("\tL1\tL2\tTotal\tMedia");
Console.WriteLine();
for (int row = 0; row < vek.GetLength(0); row++)
{
Console.Write("{0}.\t", row + 1);
for (int col = 0; col < vek.GetLength(1); col++) {
Console.Write(vek[row, col] + "\t");
sumL += vek[row, col];// SUMA
media = (double)sumL / vek.GetLength(1); //Media
if (maxL < vek[row,col])
{
maxL = vek[row, col];
}
}
Console.WriteLine(sumL + "\t" + media + "\t" + maxL);
Console.WriteLine();
}
Console.ReadKey();
}
You need to set maxL back to 0 (or, better yet, int.MinValue) at the start of each row. Simply moving its declaration into the outer for loop would be a good way to do this.
Your code gets 5, 5, 8, 8 for the maximum because, without reseting maxL, it's taking the maximum of the rows so far instead of the maximum of each row independently.
I can't figure out why I'm getting the out of range exception on the following piece of code. The values for _maxRowIndex and _maxColIndex are 5, and 0 respectively. The exception is being thrown on the first time through when row and col are both equal to 0. I don't understand why 0, 0 would be out of bounds on the array.
_cells = new ToolBarButton[_maxRowIndex, _maxColIndex];
.
.
.
for (int col = 0; col <= _maxColIndex; col++) {
for (int row = 0; row <= _maxRowIndex; row++)
{
if (_cells[row, col] == null)
{
PopulateCell(toolBarbutton, row, col);
}
}
}
Array indices start from 0 and are upto [upperbound-1]. Since your loop starts at 0, it must end at < the limit value rather than <= limit value. So, change the "<=" to "<" in the loop. Eg:
col <= _maxColIndex
should be changed to
col < _maxColIndex
If you want the max index to be 5, that means the array needs to be of length 6 as the first element is at index 0.
So, change:
_cells = new ToolBarButton[_maxRowIndex, _maxColIndex];
to:
_cells = new ToolBarButton[_maxRowIndex+1, _maxColIndex+1];
You have <= in your for statement...
So your loop evaluates for col =0, 1, 2, 3, 4 and 5... 5 is out of bounds
I guess you should declare _cells as below
_cells = new ToolBarButton[5,1];
instead of
_cells = new ToolBarButton[5,0];