This is with regard to previous question posted a while ago
Remove -1 entry from integer array
I know there are blazing fast solutions , one line answers as posted in answer section to previous posted question , but being a newbie I tried doing by for loops.
int[] arr = new int[]{ 1, -1, -1, 1 };
int[] new_arr;
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
// Console.WriteLine(arr[i]);
if (arr[i] == -1)
continue;
else
new_arr[index++] = arr[i];
}
I am getting error
Use of unassigned local variable ‘new_arr’
what am I doing wrong.
EDIT
int[] arr = new int[]{ 1, -1, -1, 1 };
int[] new_arr = new[arr.Length]; //Error being shown at this line
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == -1)
continue;
else
new_arr[index++] = arr[i];
}
for(int j=0;j<new_arr.Length;j++)
Console.WriteLine(new_arr[j]);
You haven’t initialized your array
new_arry. You need to specify its size.Inside your code you are doing:
Here since the array has not been initialized and you are trying to use it, that is why you are getting this error.
You may use
List<int>instead of the array, because it seems you are not sure about the Size of the array in your code.So your code would be:
Or the complete code can be shorten to: