Use of unassigned local variable error C# - c#

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]);

The compiler is warning that you haven't initialized the new_arr variable and you cannot use it later:
int[] new_arr = new int[arr.Length];
In this case I am initializing the new_arr array to the same size as the arr array.

You haven't initialized your array new_arry. You need to specify its size.
int[] new_arr = new int[10];
Inside your code you are doing:
new_arr[index++] = arr[i];
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:
int[] arr = new int[]{ 1, -1, -1, 1 };
List<int> tempList = new List<int>();
int[] new_arr;
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
// Console.WriteLine(arr[i]);
if (arr[i] == -1)
continue;
else
tempList.Add(arr[i]);
}
new_arr = tmepList.ToArray();
Or the complete code can be shorten to:
int new_arr = arr.Where(r=> r!= -1).ToArray();

you haven't assigned your variable new_arr. Therefore it is showing error. Your code can be like this-
int[] arr = new int[] { 1, -1, -1, 1 };
int[] new_arr = new int[4];
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];
}
for (int i = 0; i < new_arr.Length; i++)
{
Console.WriteLine(new_arr[i]);
}
You can't use any un-assigned or dangling variable in c#. Do not assign new_arr to null. It will throw null reference exception.

Related

"rotate" values in array clockwise

Firstly thank you for taking the time to look at my question.
I have a csv file of letters for which i need to get the last letter of the array and move it to the start while "pushing" the other letters across
E.G.
--Source--
a,b,c,d,[e]
--Rotated--
e,a,b,c,d
for (var i = 0; i < Array.Length - 1; i++)
{
temp = Array[Array.Length];
Array[Array.Length] = Array[Array.Length - 1];
Array[i + 1] = Array[i];
Array[i] = temp;
}
For this I am aware that not all characters would be effected but i cant think of a loop to get all values moved
Use Copy method:
int last = arr[arr.Length - 1];
Array.Copy(arr, 0, arr, 1, arr.Length - 1);
arr[0] = last;
You can shift the numbers to right by using the modulo % operator :
int[] arr = { 1, 2, 3, 4, 5 };
int[] newArr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
newArr[(i + 1) % newArr.Length] = arr[i];
}
newArr = {5,1,2,3,4}
DEMO HERE
EDIT:
Or you could make a method that shifts the numbers in your initial array without the need for creating a new array. The method rightShiftArray takes two parameters, the initial array arr an the number of shifts (shift) you want to perform:
public void rightShiftArray(ref int[] arr, int shift)
{
for (int i = 0; i < shift; i++)
{
int temp;
for (int j = 0; j < arr.Length - 1; j++)
{
temp = arr[j];
arr[j] = arr[arr.Length - 1];
arr[arr.Length - 1] = temp;
}
}
}
For example:
int[] arr = { 1, 2, 3, 4, 5 };
rightShiftArray(ref arr, 2);
The code above shifts the numbers in the initial array arr twice to the right and gives you the following output:
arr = { 4, 5, 1, 2, 3};
DEMO HERE
if you doesn't want to allocate new array, you can use this code :
newValue = Array[Array.Length-1];
for (var i = 0; i < Array.Length; i++)
{
temp = Array[i];
Array[i] = newValue;
newValue = temp;
}

Check array value inside for loop

I have to check second value in array if is equal to zero. It's working on my first example, where is user input not looped. But is not working on second example, where user input is looped.
First example
int[] array = new int[4];
array[0] = int.Parse(Console.ReadLine());
array[1] = int.Parse(Console.ReadLine());
//This statement Works here
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}
array[2] = int.Parse(Console.ReadLine());
array[3] = int.Parse(Console.ReadLine());
Second example
int[] array = new int[4];
for (int i = 0; i < array.Length; i = i + 1)
{
//Input
array[i] = int.Parse(Console.ReadLine());
//This statement is not working
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}
I think you maybe want to do that:
int[] array = new int[4];
for (int i = 0; i < array.Length; i = i + 1)
{
//Input
array[i] = int.Parse(Console.ReadLine());
if (array[i] == 0) // use i instead of 1
{
Console.WriteLine("Alert!");
}
}
I just had to write this if statement outside the loop. Now it Works
int[] array = new int[4];
for (int i = 0; i < array.Length; i = i + 1)
{
//Input
array[i] = int.Parse(Console.ReadLine());
}
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}
to be sure to acuire valid values rom user you could use int.TryParse() instead of int.Parse()
for (int i = 0; i < array.Length; i = i + 1)
{
while (!int.TryParse(Console.ReadLine(), out array[i]))
Console.WriteLine("Input an integer value!");
}
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}

Starting with the lowest value, print each value in a circular array

I have this situation:
int[] array = new int[] {7, 5, 6}
The value of my index i is 1 and it is pointing at the head of my hypothetical circular list. The value "7" at the zero position is the tail.
My aim is to print:
5,6,7
Do I need a specific structure or can I do it with a simple array?
With a single "for" loop and the modulo operator:
int[] array = new int[] {7, 5, 6};
int start = 1;
for (int idx=0; idx<array.Length; idx++)
Console.Write(array[(idx+start) % array.Length]);
There is nothing out of the box, but the following will wrap around the array.
int[] array = new int[] { 7, 5, 6 };
int startPosition = 1;
string result = "";
// Run from the start position to the end of the array
for (int i = startPosition; i < array.Length; i++)
{
result += array[i] + ",";
}
// Wrapping around, run from the beginning to the start position
for (int i = 0; i < startPosition; i++)
{
result += array[i] + ",";
}
// Output the results
result = result.TrimEnd(',');
Console.WriteLine(result);
Console.Read();
If you want to print 5,6,7 you could use:
int printIndex = 1;
for(int i = 0; i < array.Length; i++)
{
print(print(array[printIndex].ToString());
printIndex++;
if(printindex >= array.Length)
printindex = 0;
}

Delete Element from Array Using For Loop + If Statement - C#

I Have an array, TempArray[] = {1,3,-1,5,7,-1,4,10,9,-1}
I want to remove every single -1 from this array and copy the remaining arrays into a new array called Original, which should output the numbers as 1,3,5,7,4,10,9
I can only use an if statement within a for loop!
This is what I have so far, but I keep getting an error message, System.IndexOutOfRangeException
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
//error occurs at this line
//My attempt is to set the new array, Original[i] equal to TempArray[i] only where the values are not -1.
TempArray[i] = Original[i];
}
}
If you can only use If statement in for loop. This looks like a school project. First you count how many non negative numbers are there in your array. Create new array with that length and fill that array.
int[] TempArray = new int[] {1,3,-1,5,7,-1,4,10,9,-1};
int[] Original ;
int countNonNegative=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
countNonNegative++;
}
}
Original = new int[countNonNegative];
int index=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[index] = TempArray[i];
index++;
}
}
Console.WriteLine("Original Length = "+Original.Length);
using System.Linq;
int[] withoutNegativeOnes = myArray
.Where(a => a != -1)
.ToArray();
var Original = new int[TempArray.Length];
var originalCounter = 0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[originalCounter++] = TempArray[i];
}
}
Now Original may contain empty spaces at the end though, but you have all the elements which aren't -1. You can use the following code to iterate through the values:
for (int i = 0; i < originalCounter; i++)
{
Console.WriteLine(Original[i]);
}
and that's because the originalCounter has the last index values that wasn't filled from TempArray's iteration.
try this one
int[] TempArray = { 1, 3, -1, 5, 7, -1, 4, 10, 9, -1 };
int[] original = TempArray.Where(i => i != -1).ToArray();
foreach(int i in original)
Console.WriteLine(i.ToString());

C#, Finding duplicates in arrays, Index was outside the bounds of the array

Can't figure out why the line winningNumbers[i] += count; comes up as outside the bounds of the array.
static int[] CheckWinningNumbers(int[][]lottoNumbers, int[]drawNumbers)
{
int[] winningNumbers = new int[8];
for (int i = 0; i < lottoNumbers.Length; i++)
{
int k = 0;
int count = 0;
for (int j = 0; j < lottoNumbers[i].Length; j++)
{
if (lottoNumbers[i][j] == drawNumbers[k])
{
count +=1;
}
k += 1;
winningNumbers[i] += count;
}
}
return winningNumbers;
Just replace
int[] winningNumbers = new int[8];
With
int[] winningNumbers = new int[lottoNumbers.Length];
As long as you are iterating lottoNumbers.Length the variable i will not exceed its boundaries.
Edit
I ran it with the following data and it works
int[][] lottoNumbers = { new[] { 1, 2 },
new[]{ 3, 4 },
new[]{ 5, 6 },
new[]{ 7, 8 } };
int[] drawNumbers = {1, 4, 5, 8};
I don't know what data you are testing it on but you are using jagged arrays intead of multidimensional. this will not guarantee that all your sub arrays have the same length which might be problematic. If all the arrays have the same length and performance is not critical here I'd suggest you use Multidimensional Arrays

Categories

Resources