C# System.IndexOutOfRangeException or cant convert to Long [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.
I'm kinda of having this error:
"System.IndexOutOfRangeException: Index was out of the Array"
When I change int=1 to long=1 it says it can't convert long to int.
I'm trying to save all output of N into the Array and show at the end what is saved into arrays.
static void Main(string[] args)
{
int a = 0;
a = Convert.ToInt64(Console.ReadLine());
int[] array = new int[a];
if (a == 0)
{
Console.WriteLine("Falsche eingabe.");
}
else
{
long n = 1;
for (int i = 1; i <= array.Length; i++)
{
n *= i;
array[i] = n;
Console.WriteLine("N: " + i + " Fakultät von N: " + array[i]);
}
}
Console.ReadKey();
}

Indexes of arrays begin from 0 not from one. Therefore in your for loop, i <= array.Length, when i is equal to the length you enter and try array[array.Length] which throws the exception. Change to:
for (int i = 0; i < array.Length; i++)
Reason indexes are zero based is that the language is based on C where an array is a pointer to the location that was allocated for the array:
int *arrayPointer;
And then to go through the array one needs to go to arrayPointer + sizeof(int)*i. So for the first position of the array i should start from zero
In addition this line doesn't compile:
a = Convert.ToInt64(Console.ReadLine());
a is of type int while you are converting to long. Use ToInt32

Related

c# user input array for integer to look for specific number

Im new to programming i use c# to solve some problem but i have problem when user input two integer no in same-line and i want to look for zero and remove it from each no i think by replacing with the next array cell i should convert integer to string again but i cant do it please help me
string[] arr = Console.ReadLine().Split(' ');
string a = arr[0];
string b = arr[1];
int[] m = new int[1];
int[] n = new int[1];
for (int i = 0; i < a.Length; i++)
{
if (a[i] == 0 && a[a.Length - 1] != 0)
{
for (int j = i; j < a.Length; j++)
{
//****m[i] = int.Parse(a[i]); the error here cant convert from char to string ??
// a[i] = a[i + 1];**\\ Error CS0200 Property or indexer 'string.this[int]' cannot be assigned to -- it is read only**
I don't really know what you're trying to do, but if you're trying to convert the char into an ASCII value, then you would have to use the static method of Char called GetNumericValue.
Information on GetNumericValue can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.char.getnumericvalue?view=netcore-3.1

How to fix IndexOutOfRangeException [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 4 years ago.
I'm writing a Assignment for school (we are sepose to make one for the rest of the class) and I have run in to a problem. I'm having IndexOutOfRangeException errors when running the program and I can't figure out why I'm getting it.
Random rnd = new Random();
string strNumDice = tbxNumDice.Text;
int[] numDice = new int[int.Parse(strNumDice)];
int numSides = int.Parse(tbxNumSides.Text);
int trgNumber = int.Parse(tbxTarget.Text);
int sum = 0;
//int numTries = 0;
int var2 = 0;
if (int.Parse(strNumDice) * (numSides) >= trgNumber)
{
while (var2 != trgNumber)
{
tbxResult.AppendText("\n");
sum = 0;
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
tbxResult.AppendText(numDice[numberOfDice].ToString() + " ");
sum += numDice[numberOfDice];
//numTries++;
}
tbxResult.AppendText("\n");
tbxResult.AppendText("The new sum is" + sum.ToString());
var2 = sum;
}
}
If I decide to roll 6 d6's and wan't a target sum of 36 it will continue to do so until it gets to 36.
The mistake is here:
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
This is how javascript does foreach loops: you get the indexes of your array. C# gives you the values of the actual elements, rather than the indexes. As you will be modifying actual array elements, you want a for loop, rather than a foreach loop, like this:
for(int i = 0; i<numDice.Length; i++)
{
numDice[i] = rnd.Next(1, numSides+1);

What is wrong with my code (it deals with array size)?

I am initializing array size to 1 but I am updating it in the subsequent lines. It is not even storing the first element in the array as the array size is 1 initially but I expected it would. Could someone provide me with an explanation? Here is the code:
class Program
{
static void Main(string[] args)
{
int num = int.Parse(Console.ReadLine());
Console.Write("The binary number for " + num + " is ");
int size = 1;
int[] binary = new int[size];
size = 0;
while(num>=1)
{
if (num % 2 == 0)
binary[size++] = 0;
else
binary[size++] = 1;
//size += 1;
num = num / 2;
}
for (int i = size - 1; i >= 0; i--)
{
Console.Write(binary[i]);
}
Console.WriteLine();
Console.Write("The Compliment of this number is ");
for (int i = size - 1; i >= 0; i--)
{
if (binary[i] == 0)
binary[i] = 1;
else
binary[i] = 0;
}
for (int i = size - 1; i >= 0; i--)
{
Console.Write(binary[i]);
}
Console.WriteLine();
Console.ReadKey();
}
}
You cannot resize an array, it always has the length you gave it to during initialization (1 in your case).
I think the problem is specifically in your expectation that you can update an array size "in the subsequent lines."
When you make the array here:
int[] binary = new int[size];
Then the size is set in stone
When you call something like:
binary[size++] = 0;
This will not actually increase the number of slots in your array. In fact, that code is only changing the index where you are looking to read or write values. I can see that your code is going to quickly go out of bounds of the array (if you ask for anything but binary[0]
It turns out this array is a tricky data type to use; arrays have a fixed size on creation. You want something that can grow!
So you can either:
-Use an array, but declare that it's size is Math.Ciel(logbase2(yourNumber)) to make sure you will have enough space
-Use a data structure that can grow, like a string or list
-You can create a new array every time you need it bigger and assign it like:
binary = new int[++size];
binary[size-1]=whatever
Good luck, hope this helps!

Inserting into Array (C#)

I am trying to insert an int value in int array at the user input index and getting an error: Index was outside the bounds of the array. The error is in the while loop, but the solution does not use any methods like Array.Add etc.
Console.WriteLine("Enter the length of Linear Array");
int length = Convert.ToInt32(Console.ReadLine());
int[] LinearArr = new int[length];
Console.WriteLine("Maximum number of input : {0}",length);
for (int i = 0; i < LinearArr.Length; i++)
{
LinearArr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("What number you want to insert and at what index");
int InsertNum = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number :{0} and Index :{1}",InsertNum,k);
while (length>=k)
{
LinearArr[length + 1] = LinearArr[length];
length = length - 1;
}
LinearArr[k] = InsertNum;
length = length + 1;
Console.ReadLine();
Change your while loop condition from:
while (length >= k)
to:
while (length > k)
as in current condition it will access last index which is not in the array.
Another mistake is your array is of size of value in the length variable:
LinearArr[length]
and in while loop you are accessing index greater then array length:
LinearArr[length + 1] = LinearArr[length]; // length +1 will give out of bounds error
When you define
int[] LinearArr = new int[length];
the valid indexes are 0..length-1. Therefore, this expression causes an out-of-range exception:
LinearArr[length + 1] = LinearArr[length];
neither length nor length+1 are valid indexes.
In order to fix this problem, allocate enough space in the array, and start moving elements at length-1:
int[] LinearArr = new int[length+1]; // Make space for an expansion
...
while (length > k) {
LinearArr[length] = LinearArr[length-1];
length--;
}
You may want to consider using a List<int> instead of an int[] as it provides an Insert function.

How to add first n numbers in an array c#

I have an array of velocity and I want to get an array of displacement.
To get displacement for each n,i need add speed[] from 0 to n,
So I'm trying to add first n numbers for each n in array speed[],n is the index of array start from 0.
for (i = 0; i < totalnumber; i++)
{
for (int k = 0; k < i; k++)
{
Xdis[i] += Xvelo[k];
Ydis[i] += Yvelo[k];
Zdis[i] += Zvelo[k];
}
}
the loop above works,but the problem is it takes too long(loop in loop)
my question is, is there any sum function in C# can handle this without use for loop?
like Xdis[i]=Xvelo.sum(i) or sth?
Why don't you use the results you already calculated? Instead of re-summing all the way up, just use the previous result:
for (i = 1; i < totalnumber; i++)
{
Xdis[i] = XDis[i-1] + Xvelo[i-1];
Ydis[i] = YDis[i-1] + Yvelo[i-1];
Zdis[i] = ZDis[i-1] + Zvelo[i-1];
}

Categories

Resources