Index was outside the bounds of the array - c#

Friends
I have got an error which tells "Index was outside the bounds of the array" I dont know y it was happening since after completeting the for loop and entering the loop fresh again it was showing the variable value when exited from the loop before.
int[,] arrScr = new int[lstTest.Count, cnt2 + 3];
string[,] arrName = new string[lstTest.Count, cnt2 + 3];
int p;
for (i = 0; i < lstTest.Count; i++)
{
using (DataTableReader dtr3 = ds.Tables["scord_mark_table" + (i + 1).ToString()].CreateDataReader())
{
p = 0;
while (dtr3.Read())
{
arrName[i, 2 + p] = dtr3[15].ToString();
for (int k = 2; k < 12; k++)
{
arrScr[i, 2 + p] += Convert.ToInt32(dtr3[k].ToString());
}
p++;
}
}

What is in dtr3[12]? does it return null?
What is the value of cnt2?

Change k <= 12 to k < 12.
If this is not the cause of your problem you should rewrite k <= 12 to k < 13 as that is the convention most coders are used to read and write.

This means that your array does not contain as many elements as you are trying to access.

It's going to exit from the loop as k = 13 because the last valid value of k is 12, then it went through the loop, executed k++ (making it 13). At which point it fails the condition because 13 > 12 and that's when it actually exits.

Related

Problem with Heap's algorithm: not all permutations are generated

I wanted to use the recursive version of Heap's algorithm in order to get all permutations of a sequence of natural numbers from 1 to k inclusive, but ran into certain difficulties.
For k = 3, the program outputs 123, 213, 312, 132, but for some reason it does not take 231 and 321 into account. More specifically, according to the video with the implementation of the JavaScript version of the algorithm (https://www.youtube.com/watch?v=xghJNlMibX4), by the fifth permutation k should become equal to 3 (changing in the loop). I don't understand why in my case it reaches 1, and the loop stops executing.
int i, n, temp;
int[] a;
string str = "";
private void button1_Click(object sender, EventArgs e)
{
k = int.Parse(textBox1.Text);
a = new int[k];
for (i = 1; i <= k; i++)
a[i - 1] = i;
Generate(a, k);
}
private void Generate(int[] a, int k)
{
if (k == 1)
{
foreach (int digit in a)
str += digit.ToString();
listBox1.Items.Add(str);
str = "";
return;
}
Generate(a, k - 1);
for (i = 0; i < k - 1; i++)
{
if (k % 2 == 1) Swap(a, 0, k - 1);
else Swap(a, i, k - 1);
Generate(a, k - 1);
}
}
public void Swap(int[] a, int i, int j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
I focused on a variant of the algorithm found on the Wiki: https://en.wikipedia.org/wiki/Heap%27s_algorithm. Interestingly, the almost identical one which I took from here: https://www.geeksforgeeks.org/heaps-algorithm-for-generating-permutations/ works correctly.
It looks like I haven't been able to rewrite it correctly from a console application for forms.
I can try that version without recursion, but I still want to find out what my mistake was when building a recursive algorithm.
The problem is that your loop variable i is one global variable. This means that when you make a recursive call inside the loop's body, that recursion will alter the value of that loop variable. When the recursion comes back from where it was initiated, i will no longer have the same value, and the loop will exit prematurely.
So change:
for (i = 0; i < k - 1; i++)
to:
for (int i = 0; i < k - 1; i++)
It is good practice to avoid global variables, and to declare them with the smallest scope possible, there where you need them.

a program that get 10 numbers and print them in reverse order

I'm trying to write a program that takes 10 inputs and prints them in reverse order. Here is my code in c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace inverse
{
class Program
{
static void Main(string[] args)
{
int i ;
int[] n = new int[10];
Console.WriteLine("please enter 10 numbers");
for (i = 1; i <= 10; i++)
n[i] =int.Parse(Console.ReadLine());
for (i = 10; i >= 1; i--)
Console.WriteLine(n[i] + " ");
Console.ReadKey();
}
}
}
It doesn't get any errors but it also doesn't work when i'm trying to debug it. Could you please help me?
You should change your second for loop to:
for (i = 9; i >= 0; i--)
Why?
Because in you incorrect for loop, i starts at 10. In each iteration, it decrements, until i >= 1. In other words, i's value changes from 10 to 1.
But that's not how arrays work, is it? Arrays in C# are 0-based, meaning that the first item is at index 0, and the last item is at index (length - 1). In this specific case, the last item would be at index 9 (10 - 1 = 9)!
When you try to access the item at index 10, of course it throws an exception because the array ends at index 9! Also, even if it has an item at index 10, the first item of the array would not be printed because the loop stops at i = 1.
That is why you want i's value to go from 9 to 0 instead of 10 to 1.
EDIT:
I just realized you made another mistake, your first for loop is incorrect as well. It should loop from 0 to 9, not 1 to 10. This is the correct version:
for (int i = 0 ; i <= 9, i++)
Alternatively, instead of changing the loop's headers, you can just add - 1:
for (i = 1; i <= 10; i++)
n[i - 1] =int.Parse(Console.ReadLine());
for (i = 10; i >= 1; i--)
Console.WriteLine(n[i - 1] + " ");
You need to start from 0 to 9 and vice versa
for (i = 0; i <= 9 i++)
n[i] =int.Parse(Console.ReadLine());
for (i = 9; i >= 0; i--)
Console.WriteLine(n[i]);
Use the below code:
static void Main(string[] args)
{
int i;
int[] n = new int[11];
Console.WriteLine("please enter 10 numbers");
for (i = 1; i <= 10; i++)
n[i] = Convert.ToInt32((Console.ReadLine()));
for (i = 10; i >= 1; i--)
Console.WriteLine(n[i] + " ");
Console.ReadKey();
}
The problem was array index was out of range as the array starts from 0. It gave me error when I gave up to 10 inputs.

Exiting loop without break/return/if

If you have a for loop:
for(i=0;i<10;i++){}
Now, when i==5, how can I exit the for loop completely without using break, return, or if?
The best I could come up with was this:
for (int i = 0; i < 10; i++)
{
i = (i == 5) ? 10 : i;
Trace.WriteLine("i = " + i.ToString());
}
...which will cause the loop to run six times (i=0..5) and display this..
i = 0
i = 1
i = 2
i = 3
i = 4
i = 10
The alternative way to "exit the loop" (in a particularly nasty fashion) would be to do this...
for (int i = 0; i < 10; i++)
{
int a = 3 / ((i == 5) ? 0 : 1);
Trace.WriteLine("i = " + i.ToString());
}
..which crashes out, errr, successfully exits the loop without using the break, return or if commands.
i = 0
i = 1
i = 2
i = 3
i = 4
A first chance exception of type 'System.DivideByZeroException' occurred in MikesProgram.dll
language is C# .it was an interview question actually..curious
Do I get the job ?
I would need to check your health & dental plans, and I have to leave early on Thursdays to collect my daughters from school.
;-)
for (int n = 0; n < 10; n++)
{
n += (n / 5) * 5;
}
well here's another way if you want to break the processing exactly when i = 5 without using break, return, or if
for (int lowsetLimit = 0, highestLimit = 10, i = lowsetLimit; i < highestLimit; i++)
{
//normal code which process before i gets eqaul to 5 goes here...
i = (i < 5) ? i : highestLimit; //and here is the pivot point.
}
for(i=0;i<10;i++){
(i==5) ? goto Outer : //do something;
}
Outer:
//do something
The question says that loop should end when i=5, It says nothing about start, So this should be valid (ternary operator solution is better, but if we are not allowed to use any conditional operator)
for (int i = 0; i < 10; i++)
{
i=i-4;
Console.WriteLine("i = " + i.ToString());
i=i+4;
}
this Starts at -4 and ends at 5.
The real answer of course would be the following:
for (i=0; i!=5; i++)
{
// do something
}
But let's make it a bit more generic: stop if (expression) becomes true.
The second argument of the for loop is a boolean expression which determines whether to continue the loop with the next element or not.
So if you want to stop looping because of any condition:
for (i=0; !(expression) && i<10; i++)
{
// do something
}
This works using while and goto:
for (int i = 0; i < 10; i++)
{
while (i < 5)
{
Console.Write(i + " ");
goto OutsideWhile;
}
OutsideWhile:
continue;
}
// 0 1 2 3 4

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

C# & VS error: "make sure that the maximum index on a list is less than the list size"

I faced the error mentioned in the title when doing my homework, and simply can't find a way to remove it. Here is the method that I have this problem with:
public static double LaskeMiidi(double[] luvut)
{
double ka = Keskiarvo(luvut);
double miidi = luvut[0];
for (int i = 0; i < luvut.Length; i++)
{
if (luvut[i] - ka < luvut[i + 1] - ka) // The line error points to!
{
miidi = luvut[i];
}
else
{
miidi = luvut[i + 1];
}
}
return miidi;
}
So basically the problem is that when I say luvut[i + 1], at some point this index might become more than the length of the array is. I just can't figure out any ways to solve this problem, since I'm only a beginner with programming.
Yes, this is the problem:
for (int i = 0; i < luvut.Length; i++)
{
if (luvut[i] - ka < luvut[i + 1] - ka)
When i is luvut.Length - 1, then i + 1 will be luvut.Length - and therefore an invalid index. (For an array of length x, the valid indexes are 0 to x - 1 inclusive.) You probably want to end one iteration earlier:
for (int i = 0; i < luvut.Length - 1; i++)
That way i + 1 will still be a valid index in the array - both in the if condition and in the body of the else clause.
End your loop earlier:
for (int i = 0; i < luvut.Length - 1; i++)
This stops the loop ever getting to the point where an index would be invalid.
When i = luvut.Length -1, luvut[i + 1] will give an error as it is beyond the array bounds.
You need either:
for (int i = 0; i < luvut.Length - 1; i++)
Or else handle the luvut[i + 1] issue in another way in another If block.
Notice that when you define an array, range of items are between 0 and array.length-1. so you should write:
for (int i = 0; i < luvut.Length-1; i++)

Categories

Resources