I am trying to make a C# for loop that will loop through an array of items and print the first date of the user. Below is the code for the array (which i think is correct).
string[,] arrHolidays = new string[2, 3];
arrHolidays[0, 0] = "10/05/2015";
arrHolidays[0, 1] = "15/05/2015";
arrHolidays[0, 2] = "Danny";
arrHolidays[1, 0] = "20/05/2015";
arrHolidays[1, 1] = "22/05/2015";
arrHolidays[1, 2] = "Kieran";
Below is the code for the For loop (which is throwing the error)
for(int i = 0; i < arrHolidays.Length; i++)
{
Console.WriteLine(arrHolidays[i, 0]);
}
Index out of range exception was unhandled. this is the error I am recieving. When it throws the error and I check the value of 1 it is 2 if this is any help in resolving it.
What I am expecting to see is this in the console app:
10/05/2015
20/05/2015
INB4 I have hardly any c# experience this is my first project, so please explain any help :)
You must use GetLength method, not the Length property.
The Length property for a multi-dimensional array returns the total count of all the items in the array. The GetLength method returns the number of size of a given dimension (where dimension is specified as a zero-based index).
So, arrHolidays.Length will return 6.
Change for loop to:
for (int i = 0; i < arrHolidays.GetLength(0); i++)
{
Console.WriteLine(arrHolidays[i, 0]);
}
Array.GetLength(int dimension)
In your case, you want to get the length of the first dimension, so arrHolidays.GetLength(0).
Related
I answered a LeetCode question by the name of 'Remove Duplicates from Sorted Array' in two similar languages to prepare for different interviews. My Java solution was marked as correct, but the C# solution throws a Runtime Error with the message Unhandled exception. System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
My correct solution in Java is as follows:
public int removeDuplicates(int[] nums) {
int pointer1 = 0;
for (int pointer2 = 1; pointer2 < nums.length; pointer2++) {
if (nums[pointer1] != nums[pointer2]) {
pointer1++;
nums[pointer1] = nums[pointer2];
}
}
return pointer1 + 1;
}
My incorrect solution in C# is as follows:
public int RemoveDuplicates(int[] nums)
{
int pointer1 = 0;
for (int pointer2 = 1; pointer2 < nums.Length; pointer2++)
{
if (nums[pointer1] != nums[pointer2])
{
pointer1++;
nums[pointer1] = nums[pointer2];
}
}
return pointer1 + 1;
}
The requirement was to do this in-place, so I avoided using extra memory. I'm having trouble understanding why length was out of bounds for the array when I specified the length within the loop's scope. Also this error is only thrown when attempting the C# solution. I'm working to get better at C# and would like to know what the issue with my implementation is. Thank you for any and all feedback.
It's probably not your code that's throwing, since the only OutOfRange exception you would get from it would be "Index out of bounds", not "Offset and length out of bounds". Whatever calls your code throws.
It probably tries to run your method on an empty array or a null, try returning 0 or -1 when nums.Length == 0 or nums == null.
(From comments: yep, it expected 0 when an empty array was passed as argument. The check needed was:
if (nums.Length == 0)
return 0;
).
This is my first stack overflow post so sorry if its not in the right format. In any case, the following is in C# and I'm using Visual Studio 2019 .NET Core 3.1
Goal: Sorting an Array of integers in ascending order ex. [3, 2, 5, 1] -> [1, 2, 3, 5]
Problem: Method sorts everything but the first element ex. [3, 2, 5, 1] -> [3, 1, 2, 5]
Code:
for (int i = 0; i < array.Length; i++)
{
if(i != array.Length - 1 && array[i] > array[i + 1])
{
int lowerValue = array[i + 1];
int higherValue = array[i];
array[i] = lowerValue;
array[i + 1] = higherValue;
i = 0;
}
}
I've put in Console.WriteLine() statements(one outside of the for loop above to see the starting array and one in the if statement to see how it updates the array when a change happens and yes I know I could use the debugger, but I don't currently have any method calls to the method this for loop is in) to see how its adjusting the array as it goes along and it will regularly show that its running through an iteration without changing anything.
Also if anyone could tell me what the time complexity of this is, that would be great. My initial guess is that its linear but I feel like with the "i = 0" statement and the way it swaps values makes it exponential. Thanks!
When I run your code, I get 2135
As #Flydog57 says, it would be useful to go through every single step to notice when it doesn't run as desired. The code looks a bit like a BubbleSort without inner loop... The iteration also goes through only once. If I see it correctly, you are missing a multiple iteration. Have a look at the BubleSort.
My suggestion for the sorting looks like this:
int[] array = { 3, 2, 5, 1 };
var sortedArray = array.OrderBy(p => p).ToArray();
Regarding O notation, I am unfortunately a bit rusty and can't help. But for me it looks like O(n).
Your algorithm is not a variant of bubble sort and it reset the loop counter when facing to descending order. in Bubble sort in every traverse, we are sure that the global max/min is in the right place but your algorithm is not sure about that till the execution for the last i.
In your algorithm, the left part of the array is always partially ordered.
Firstly, the problem with your code is that after resetting the counter, the loop would add it up to 1(i++), therefore in your code, it can't be less than 1. if you set it to -1 it would sort the array, because after setting it to -1 the loop changes it to 0 and that's the desired behavior. The if block should be like this:
if(i != array.Length - 1 && array[i] > array[i + 1])
{
int lowerValue = array[i + 1];
int higherValue = array[i];
array[i] = lowerValue;
array[i + 1] = higherValue;
i = -1;
}
The order of the algorithm: The worst-case happens when the array is in descending order, and in this case, for every i, The if condition would be true then the i would be reset to zero, therefore the total time complexity would be:
1 + 2 + 3 + 4 + .. + n(array length)= n(n+1)/2= O(n^2)
I'm running this code, but every time, I get the error "An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred" on the first line of the for loop. Its basically code for a multiple choice quiz question, with questions & answers stored in a 2d array.
Unfortunately, I can't seem to spot the problem. It's probably a simple error, but I'm a beginner so I'm struggling to spot it.
I've read through similar questions, but I don't understand why this line is causing problems. I've got 4 elements in my list, one is removed before the loop, so there should be 3 left. I'm only looping through 3 times, so I don't understand what the problem is.
Hopefully someone will be able to help, Thanks!
Random rndq = new Random();
Random rnda = new Random();
List<int> answers = new List<int> { 1, 2, 3, 4 };
int questionchoice = rndq.Next(0, questions.GetLength(0) - 1);
int labelchoice = rnda.Next(0, answers.Count-1);
lblQuestion.Text = questions[questionchoice, 0];
var answer = (Label)Controls["lblAns" + answers[labelchoice]];
answer.Text = questions[questionchoice, 1];
answers.Remove(labelchoice);
int j = 2;
for (int i = 0; i < 3; i++)
{
var wronganswers = (Label)Controls["lblAns" + answers[i]];
wronganswers.Text = questions[questionchoice, j];
answers.RemoveAt(i);
j++;
}
Each pass through the loop you're removing an item from the list. After the first pass your list has 3 items in it [2, 3, 4]. Next pass there are two items left [2, 4]. Then you try to get the third item from the list of two and get an exception.
Either you need to leave the list alone while looping or make sure that your loop condition actually references the length of the list. Assuming that you want to actually process all 4 items I would suggest that you remove the RemoveAt call completely.
Or if you actually want to remove the items, reverse the direction of your loop:
for (int i = answers.Count - 1; i >= 0; i--)
{
// ....
answers.RemoveAt(i);
}
This will still process all of the items in the list and leave you with nothing in the list at the end.
The program I'm writing, is suppose to create an array, read its size and inputs from an .txt-file.
Print it out in a new .txt-file, with the transpose of the matrix(array) and the max-value in the array.
The content of the .txt-file is like a downward list. The first two numbers are to set the sizes of the arrays, the following numbers below are the numbers inside it.
The code works almost as I want it.. as of now, it can read arrays with the same length of columns and rows - as in 5x5, 8x8 etc. print out the transpose and find the max-value.
Here's the problem
But I need it to also be able to make arrays the size of 3x4, 4x5, 5x8 etc, and do all the things i mentioned above.
I'm greeted with the error System.IndexOutOfRangeException as I try to run it.
Here's how my code looks right now: Full Code Example
int column = Convert.ToInt32(sr.ReadLine()); //Reads value from txt
int row = Convert.ToInt32(sr.ReadLine()); //Reads value from txt
int[,] Matris = new int[row, column]; //Creates 2D array
//For-loop for "input"
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
Matris[i, j] = Convert.ToInt32(sr.ReadLine()); //Saves values to array. HERE'S WHERE I GET THE ERROR.
}
}
row and column are swapped. Make the declaration of the array like this:
int[,] Matris = new int[column,row];
or swap the indices in the loop.
I'm having trouble with part of an array, I need to create a three dimensional array in a console program that starts empty and will have user assigned values after asking for user input. It does not need to persist past the initialization of the program.
I've created a few arrays that have values already in place to call upon, but I've never had to create an array that took the user's values that could then be called.
You can create an array of a specific size by specifying the size inside the brackets, then you can fill in the data later. Here's a sample of a three dimensional array with user-specified size.
Console.WriteLine("Enter length of arrays (three dimensions, comma separated)");
string line = Console.ReadLine();
string[] stringDimensions = line.Split(',');
int[] intDimensions = stringDimensions.Select(s => Convert.ToInt32(s)).ToArray();
var array = new string[intDimensions[0],intDimensions[1],intDimensions[2]];
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
for (int k = 0; k < array.GetLength(2); k++)
{
array[i, j, k] = String.Format("{0}.{1}.{2}", i, j, k);
}
}
}
All arrays start out empty, that is all items in the array is set to the default value of the class. If it's an array of strings, for example, all items start out as null.
If it's an array of int, then all items start out as zero, so you would rather want an array of int? so that all items start out as null.
If by empty, you mean zero items, then you shouldn't use arrays, you should use a List<T>. They start out with zero items, then you add items to populate it.
Try using ArrayList:
ArrayList mainArrayList = new ArrayList();
//creating a three dimensional arraylist
mainArrayList.Add(new ArrayList());
mainArrayList.Add(new ArrayList());
mainArrayList.Add(new ArrayList());
(mainArrayList[0] as ArrayList).Capacity = userSpecifiedSizeX;
(mainArrayList[1] as ArrayList).Capacity = userSpecifiedSizeY;
(mainArrayList[2] as ArrayList).Capacity = userSpecifiedSizeZ;