How can I add int values to a c# array [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 2 years ago.
I have an array numArray with the length set to a value the user can put in. if arrayLength is 5 for example I want the for loop to count up by 1 to 5 [1,2,3,4,5]. My error is numArray[i] = sum + 1; (System.IndexOutOfRangeException: 'Index was outside the bounds of the array.')
int[] numArray = new int[arrayLength];
int sum = 0;
for (int i = 0; i <= arrayLength; i++)
{
Console.WriteLine(i);
numArray[i] = sum + 1;
}

Use i < arrayLength.
If i <= arrayLength at the last iteration i = 5 and you try to access numArray[5] which does not exists (you have only 5 indexes: 0 to 4 ).

Related

How to avoid my array from being reassigned values as I progress through my loop? [duplicate]

This question already has answers here:
Passing Arrays by Value and by Reference
(4 answers)
Copy array with `ToArray` Method
(2 answers)
Any faster way of copying arrays in C#?
(5 answers)
Closed 1 year ago.
Here is my code below-
double[][] geometricReturnsArray = new double[returnsArray.Count][];;
double[] tempGeometricReturns = new double[returnsArray[0].Count];
double return_1 = 0;
double return_2 = 0;
for (int i = 0; i < returnsArray.Count; i++)
{
for (int j = 0; j < returnsArray[i].Count - 1; j++)
{
return_1 = returnsArray[i][j + 1];
return_2 = returnsArray[i][j];
tempGeometricReturns[j] = ((return_1 - return_2) / return_2) * 100;
}
geometricReturnsArray[i] = tempGeometricReturns;
}
The issue I'm facing in the code is that tempGeometricReturns keeps getting reassigned as i increases. So in the end, all three arrays of geometricReturnsArray have exactly the same values since when tempGeometricReturns gets reassigned, so do the previous values in geometricReturnsArray.
I tried to use lists as well but then I just get a long list of 267 values whereas I'd prefer three arrays of length 90. What else can I try to do?
In your example you will end up with multiple references to the same array in the geometricReturnsArray. Arrays are reference types, so assignments only copy the reference, not the entire array.
The fix is to create a new array for each outer loop, for example by copying the existing array when doing the assignment
}
geometricReturnsArray[i] = tempGeometricReturns.ToArray();
}
or
for (int i = 0; i < returnsArray.Count; i++)
{
double[] tempGeometricReturns = new double[returnsArray[0].Count];
for (int j = 0; j < returnsArray[i].Count - 1; j++)
{

MergeSort Algorithm "IndexOutOfRangeException" [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
I've been reading the Introduction to Algorithms and tried to implement the pseudocode, but I can't seem to pinpoint what is causing IndexOutOfRangeException.
Merge
The error happens at left[i] < right[j]
static void Merge(int[] array, int start, int middle, int end)
{
i = 1;
j = 1;
for (k = start; k < end; k++)
{
if (left[i] < right[j])
{
array[k] = left[i];
i = i + 1; // -> i++;
}
else
{
array[k] = right[j];
j = j + 1; // -> j++;
}
}
}
Solved
I solved it by setting all i and j variables to 0 and k to k = start - 1
You are getting error in this line:
if (left[i] < right[j])
since i exceeds left array length when it becomes 6 and array left has only 6 elements.
It is very easy to figure it out when you use debugging.

How can i read variables to an array? [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I am learning C#. I know how to do this in C++ but i get an exception to this line of code :
v[i] = int.Parse(Console.ReadLine());
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
int[] v = new int[n];
for (int i = 1; i <= n; i++)
{
v[i] = int.Parse(Console.ReadLine());
}
I want to translate this from C++ to C#:
int v[1001], n;
cin>>n;
for (int i = 1; i <= n; i++)
{
cin>>v[i];
}
There is more code but i think it's irelevant for this problem.
Just to add the code which will work, alongside Christos' explanation.
Solution: Now you're also starting the loop at 0 which will not result in an exception and you won't skip the first element.
Note that here you have < not <=. That's because the last element in the array has an index of n-1.
int[] v = new int[n];
for (int i = 0; i < n; i++)
{
v[i] = int.Parse(Console.ReadLine());
}
As already mentionend, for a detailed explanation/comparison(between c++ and c#) on this see Christos' answer.

Data cannot be assigned [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
Hello why in this function data could not be read(assigned)?
Error is in the line with comments(Object reference not set to an instance of an object.)
protected static int[][] GetMapFromFile(ref int size)
{
using (StreamReader sr = new StreamReader(#"C:\Users\doman\OneDrive\Desktop\Antras semestras\Programavimas\Laboras1\Laboras1\Duomenys.txt"))
{
string skyr = " ,.;";
size = Convert.ToInt32(sr.ReadLine());
int[][] map = new int[size][];
for (int i = 0; i < size; i++)
{
string line = sr.ReadLine();
string[] values = line.Split(skyr.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < values.Length; j++)
{
map[i][j] = Convert.ToInt32(values[j]); // Error here
Console.Write(map[i][j]);
}
Console.WriteLine();
}
return map;
}
}
My data file
5
0 1 3 4 2
1 0 4 2 6
3 4 0 7 1
4 2 7 0 7
2 6 1 7 0
You need to create each "sub" array. Add map[i] = new int[values.Length] before the second for loop.

C# array wont accept "size" [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
the noob, again. todays question is:
int[] forArray = new int[10];
for (int k = 1; k <= 10; k++)
{
forArray[k] = k * 2;
Console.WriteLine(k); // test
}
for (int k = 0; k < 10; k++)
{
Console.WriteLine(forArray[k]);
}
it gives an "out of bounds" error. I would like my program to output natural numbers from 2 to 20. Instead gives off an error. when I change the first for loops condition to k <= 9 it runs but gives me 0 instead of 20. its like it returns the last value as 0 and "re-positions" it to the "front". sorry for the really simple question.
Arrays are zero-based, when it comes to referencing the elements. So, for 10 items in an array (which is what you allocated), it's forArray[0] through forArray[9]. Your code tries to loop from forArray[1] through forArray[10], and there is no index position 10 (which is when you end up going out of bounds).
Your second for-loop is fine, as it goes from 0 to 9.
Note: Since your loop needs to be zero-based, you'll need to adjust how you calculate the number you stuff into the index positions, if you want it starting with 2.
Debug your code and step through, as you see below you are trying to assign to index [10], which doesn't exist.
{
int[] forArray = new int[10];
for (int k = 1; k < 10; k++) // k < 10 instead of k <= 10
{
forArray[k] = k * 2;
Console.WriteLine(k); // test
//forArray[0] = SKIPPED
//forArray[1] = 2
//forArray[2] = 4
//forArray[3] = 6
//forArray[4] = 8
//forArray[5] = 10
//forArray[6] = 12
//forArray[7] = 14
//forArray[8] = 16
//forArray[9] = 18
//forArray[10] INVALID
}
for (int k = 0; k < 10; k++)
{
Console.WriteLine(forArray[k]);
}
}
Tested here
Change your condition to k
forArray[k - 1] = k * 2;

Categories