C# array wont accept "size" [duplicate] - c#

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;

Related

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 add int values to a c# array [duplicate]

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 ).

How to print below Star pattern

I can't get this answer:
*****
****
***
**
*
Multidimensional arrays, nested (do..while, while, for)
char[,] stars = new char[5, 3];
for (int i = 0; i < 5; i++)
{
for(int x=0;x<3;x++)
{
stars[i,x]=char.Parse("*");
Console.Write(stars[i, x]);
I want to get 5 "*" stars then 4 in a new Line then 3 in a new Line then 1 in a new Line
Here you need to understand pattern behind *.
star pattern in your program is,
0st Line : 5 starts //Considering starting index is 0
1st Line : 4 starts // starts = n starts - Line no. where n = 5
2nd Line : 3 starts
3rd Line : 2 starts
4th Line : 1 starts
i.e.
Number of stars in single line = n starts - Line number //
where n = 5
So your code will look like,
int n = 5;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{ //^^^^^ n - i is key behind this * pattern
Console.Write("*");
}
Console.WriteLine();
}
As this is not about array indexing or address calculation but actual countable objects (stars), I feel that 1-based indexes make more sense here.
Also, the number of stars should be decreasing, so counting backwards makes more sense as well:
for (int numStars = 5; numStars >= 1; --numStars)
{
for (int star = 1; star <= numStars; ++star)
Console.Write("*");
Console.WriteLine();
}

Sort an array of 0s, 1s and 2s (Further optimization) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
Below is a very simple code which sorts array of 0s, 1s and 2s. I believe it's time complexity is O(N), right? How can this algo be further improved to bring down time complexity to O(logN) or so?
//Input: 0 2 1 2 0
//Output: 0 0 1 2 2
public static int[] SortArray012(int[] array)
{
Dictionary<int, int> result = new Dictionary<int, int>(3);
int[] sortedResult = new int[array.Length];
int i = 0;
foreach(int no in array)
{
if (result.ContainsKey(no))
result[no]++;
else
result.Add(no, 1);
}
for (; i < result[0]; i++)
sortedResult[i] = 0;
for (; i < result[0] + result[1]; i++)
sortedResult[i] = 1;
for (; i < result[0] + result[1] + result[2]; i++)
sortedResult[i] = 2;
return sortedResult;
}
This is an example of counting sort. While there is no way to my knowledge to lower the asymptotic complexity you can focus on reducing the constants. For example there is no need to construct a dictionary, an array will do. If we are guaranteed that we will only see 1,2 and 0 then there is no need for the if statement. We can also generate our result with two for loops instead of three
int[] test = {1,1,0,2,1,0};
int[] count = {0,0,0};
int[] result = new int[test.Length];
foreach(int no in test){
count[no]++;
}
int i = 0;
int k = 0;
foreach(int c in count){
for(int j = 0; j < c; j++){
result[k++] = i;
}
i++;
}

Adding array to a list how to stop it being the last iteration data? [duplicate]

This question already has answers here:
C# dictionary value clearing out when I clear list previously assigned to it....why?
(6 answers)
Closed 6 years ago.
I am trying to create a list of an array of 2 items. The problem I have is the final iteration in my loop sets all the list's arrays to the same (my guess is due to a reference?). I was wondering how I can prevent this from happening.
This is what I am trying to do:
PathTiles[] links = new PathTiles[2];
int j;
for(int i = 0; i < path.Count; i++)
{
if(i+1 < path.Count)
{
links[0] = path[i];
links[1] = path[i];
for(j = i+1; j < path.Count; j++)
{
if(path[j].x == links[1].x && Mathf.Abs(path[j].y-links[1].y) == 1)
{
links[1] = path[j];
i = j;
}
else
{
break;
}
}
validPath.Add(links);
for(int k = 0; k < validPath.Count;k++)
{
Debug.Log(validPath[k].x+", "+validPath[k].y);
}
Debug.Log("=====");
}
}
So the console shows this:
0, 0
=====
1, 1 <-- why did this become 1, 1 and not stay as 0, 0
1, 1
=====
Does any one know how I can retain the first data value and not have it overwritten? I am currently under the impression it is because it stores a reference and so I changed the values, but I don't know how to stop it doing that.
Try adding the PathTiles[] links = new PathTiles[2]; within the 1st for loop statement. As you said this is a problem of references. As you were addiing the same modified links to the list. the 1st data value is overwritten.
int j;
for (int i = 0; i < path.Count; i++)
{
PathTiles[] links = new PathTiles[2]; //<-- here
if (i + 1 < path.Count)
{
links[0] = path[i];
links[1] = path[i];
...

Categories