Delete Element from Array Using For Loop + If Statement - C# - 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());

Related

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;
}

Deleting Duplicates From An Array

I have a code where I load up a text file and save it as an array. The array contains a list of numbers with some of the numbers being duplicated. In my code I first loop through the array and replace all duplicated numbers with a -1. Then I plan on deleting all the -1 values from my array. The remaining array values (non duplicates) are then copied on to a new array to be outputted.
However I keep getting an error when I attempt to delete the -1 values from my array (see code below). I don't know why this is happening so if anyone knows anything please let me know!
P.S. This is school project so I can only use loops and if statements, not things like LINQ or foreach, etc.
public partial class Form1 : Form
{
//Global Variable
int[] Original;
public Form1()
{
InitializeComponent();
}
//Exit Application
private void mnuExit_Click_1(object sender, EventArgs e)
{
this.Close();
}
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//Code to Load the Numbers From a File
OpenFileDialog fd = new OpenFileDialog();
//Open the File Dialog and Check If A File Was Selected
if (fd.ShowDialog() == DialogResult.OK)
{
//Open File to Read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
//Go Through Text File
for (int i = 0; i < Records; i++)
{
Original[i] = int.Parse(sr.ReadLine());
}
}
}
private void btnOutput_Click(object sender, EventArgs e)
{
//Store Original Array
string Output = "Original \n";
//Output Original Array
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
//Create TempArray
int[] TempArray = new int[Original.Length];
//Set TempArray Equal to Original Array
for (int i = 0; i < Original.Length; i++)
{
TempArray[i] = Original[i];
}
//Duplicate Number Counter
int Counter = 0;
//Loop Through Entire Array
for (int i = 0; i < TempArray.Length; i++)
{
for (int j = i + 1; j < TempArray.Length; j++)
{
//Replace Duplicate Values With '-1'
if (TempArray[i] == TempArray[j])
{
TempArray[j] = -1;
Counter++;
}
}
}
//Set Size of Original Array
Original = new int[Original.Length - Counter];
//Remove -1 Values
//Index Counter
int Index = 0;
//error starts
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[Index] = TempArray[i];
Index++;
}
}
//error ends
//Final Output -- The New Array
Output = Output + "Original Without Duplicates\n";
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
lblOutput.Text = Output;
}
}
}
Reverse the line TempArray[i] = Original[Index]; to Original[Index] = TempArray[i];
The only thing you need to do in this case would be
Original = new int[Original.Length - (Counter-1)];
and yes you need to change the code to assign the values to Original instead of TempArray.
//error starts
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[Index] = TempArray[i];
Index++;
}
}
//error ends
Let's say you have three 3's in your array. In the outer loop when you iterate and come across a 3, you set the other two 3's to -1. Now you come across the first -1 which earlier was a 3 and you have already set the last 3 to -1. Now you search for duplicates and wrongly calculate your number of duplicates in the Duplicate Number Counter (called Counter) because for you -1 is a duplicate of -1.
So, what you can do is this:
First only set all duplicates to -1 and then count the number of -1's by looping through the array again. This way you will set correctly the size of non-duplicated array elements.
To set all dups to -1:
for (int outerIndex = 0; outerIndex < Original.Length; outerIndex++)
{
var currentElement = Original[outerIndex];
for (int innerIndex = outerIndex + 1; innerIndex < Original.Length; innerIndex++)
{
if (Original[innerIndex] == currentElement) Original[innerIndex] = -1;
}
}
To get the count of non-repeating elements now:
var counter = 0;
for (int index = 0; index < Original.Length; index++)
{
if (Original[index] != -1) counter++;
}
Creating non-duplicated elements' array:
var newArrayIndex = 0;
var newArray = new int[Original.Length - counter]; //Calculated counter above
for(int i = 0; i < Original.Length; i++)
{
if (Original[i] != -1) newArray[newArrayIndex++] = Original[i];
}
//Finally, not good programming practice, but
//you can set Original to this newArray if you like...
Original = newArray;

How do you go through two int arrays and sum their values if they exist

I want to create a method that I can send two arrays (that will be containing ints). These arrays wont necessarily be equally long. for example first array could have an index of 15 while the second array has an index of 12. in that case I want to add array1 and array2 for the first 12 then just get the value of array1 for the last 3.
I thought something like this:
int[] ArrTotal(int[] array1, int[] array2)
{
int[] total = new int[15];
for (int i = 0; i < 15; i++)
{
if (array1[i] != null && array2[i] != null)
{
total[i] = array1[i] + array2[i];
}
else if(array1[i] != null)
{
total[i] = array1[i];
}
else if (array2[i] != null)
{
total[i] = array2[i];
}
else
{
total[i] = 0;
}
}
return total;
}
Problem is that I can't check and see if an int array is null. I read something about doing an:
If(i < array1.Length)
but that does not seem to work either, it says it will always be true in my case.
Am I on the right track at all or is there some major flaw I'm missing? :)
How about:
int[] ArrTotal(int[] a, int[] b)
{
if (a == null || b == null)
{
return (int[])(a ?? b).Clone();
}
int length = Math.Max(a.Length, b.Length);
int[] result = new int[length];
for (int i = 0; i < length; i++)
{
int sum = 0;
if (a.Length > i) sum += a[i];
if (b.Length > i) sum += b[i];
result[i] = sum;
}
return result;
}
Try to check lengths of both arrays before:
int length = (array1.Length < array2.Length ? array1.Length : array2.Length);
Then iterate and assign only to array indeces from 0 to length of the shorter array - 1:
for (int i = 0; i < 15; i++)
if (i < length)
newArray[i] = array1[i] + array2[i];
else
newArray[i] = 0;
int[] a1 = new int[] { 1, 2, 3, 2, 3, 1 };
int[] a2 = new int[] { 1, 2, 3, 2, 3, 1, 3, 2, 3 };
List<int> r = new List<int>();
bool a1_longer = (a1.Length > a2.Length);
int length_diff = Math.Abs(a1.Length - a2.Length);
int length = (a1_longer ? a2.Length : a1.Length);
for (int i = 0; i < length; i++) r.Add(a1[i] + a2[i]);
for (int i = 0; i < length_diff; i++) {
r.Add(a1_longer ? a1[length + i] : a2[length+i]);
}
r.ToArray();
You may use Linq for it:
int[] ArrTotal(int[] array1, int[] array2)
{
return Enumerable.Repeat(0, Math.Max(array1.Length,array2.Length))
.Select((a, index) => a +
((array1.Length > index) ? array1[index] : 0)+
((array2.Length > index) ? array2[index] : 0))
.ToArray();
}
Using Linq you can do this (which will handle null arrays). You will need a using System.Linq at the top of the source code file:
int[] ArrTotal(int[] array1, int[] array2)
{
if ((array1 == null) && (array2 == null))
return new int[0]; // Zero length array - put some other number here if you need!
else if (array1 == null)
return (int[])array2.Clone(); // Result will just be a copy of the non-null array.
else if (array2 == null)
return (int[]) array1.Clone(); // Result will just be a copy of the non-null array.
else
{
int skip = Math.Min(array1.Length, array2.Length);
return Enumerable
.Zip(array1, array2, (i1, i2) => i1 + i2)
.Concat(array1.Skip(skip))
.Concat(array2.Skip(skip))
.ToArray();
}
}

Use of unassigned local variable error 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.

Categories

Resources