Index Out Of Range while comparing two array elements [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
This is a part of a bigger problem I'm trying to solve, but index out of range exception seems to be an invisible hurdle to me.
This if loop works well in c++ but in c#, idk whats happening. Any help is appreciated. This is very important to me. Please find the root for this exception.
namespace damn
{
class Program
{
static void Main(string[] args)
{
string InputString = Console.ReadLine();
string[] stringArray = InputString.Split(',');
int[] intArray = new int[stringArray.Length];
for (int i = 0; i < stringArray.Length; i++)
{
intArray[i] = int.Parse(stringArray[i]);
}
int length = stringArray.Length;
for(int i=0; i<length; i++)
{
if (intArray[i] > intArray[i + 1])
Console.WriteLine("ok");
else
Console.WriteLine("not ok");
}
}
IndexOutOfRangeException was unhandeled.But how? the logic is right, ain't it?
Call me a noob or what ever, this is not the actual program, but a part of it.
input sample -
1,2,3,4 [/enter/]

You have int Array[i + 1] where i goes one less than length so for last item you will have out of range as array is zero-based index; end loop 2 less then length so that intArray[i + 1] wont go out of range.
for(int i=0; i<length-1; i++)

your second loop is out of range doens't matter if you're using C++ or C#. it's just that iin C++ you have to manage your own memory space and it doesn't throw index out of range error; so you need to know when to stop in C++.
Let's get back to your code:
for(int i=0; i<length; i++)
{
if (intArray[i] > intArray[i + 1])
Console.WriteLine("ok");
else
Console.WriteLine("not ok");
}
When i == length - 1 which is your last true condition, i+1 is out of range of the array because i + 1 = length; and in C# index starts from 0.
to fix just simply change your second loop condition to i < length - 1 instead of i < length

Related

Increasing sequence in one dimensional array

You're given an array of integers,in case if you see subsequence in which each following bigger than the previous on one(2 3 4 5) you have to rewrite this subsequence in the resulting array like this 2 - 5 and then the rest of the array. So in general what is expected when you have 1 2 3 5 8 10 11 12 13 14 15 the output should be something like 1-3 5 8 10-15.
I have my own idea but can't really implement it so all I managed to do is:
static void CompactArray(int[] arr)
{
int[] newArr = new int[arr.length];
int l = 0;
for (int i = 0,k=1; i <arr.length ; i+=k,k=1) {
if(arr[i+1]==arr[i]+1)
{
int j = i;
while (arr[j+1]==arr[j]+1)
{
j++;
k++;
}
if (k>1)
{
}
}
else if(k==1)
{
newArr[i] = arr[i];
}
}
In short here I walk through the array and checking if next element is sum of one and previous array element and if so I'm starting to walk as long as condition is true and after that i just rewriting elements under indices and then move to the next.
I expect that people will help me to develop my own solution by giving me suggestions instead of throwing their own based on the tools which language provides because I had that situation on the russian forum and it didn't help me, and also I hope that my explanation is clear because eng isn't my native language so sorry for possible mistakes.
If I understand the problem correctly, you just need to print the result on the screen, so I'd start with declaring the variable which will hold our result string.
var result = string.Empty
Not using other array to store the state will help us keep the code clean and much more readable.
Let's now focus on the main logic. We'd like to loop over the array.
for (int i = 0; i < array.Length; i++)
{
// Let's store the initial index of current iteration.
var beginningIndex = i;
// Jump to the next element, as long as:
// - it exists (i + 1 < array.Length)
// - and it is greater from current element by 1 (array[i] == array[i+1] - 1)
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
// If the current element is the same as the one we started with, add it to the result string.
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
// If it is different element, add the range from beginning element to the one we ended with.
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
All that's left is printing the result:
Console.WriteLine(result)
Combining it all together would make the whole function look like:
static void CompactArray(int[] array)
{
var result = string.Empty;
for (int i = 0; i < array.Length; i++)
{
var beginningIndex = i;
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
Console.WriteLine(result);
}

Simple C# program using arrays throws an error

Well I'm trying to write a program in which if you add for example 3 integers in the array, let's say 3 2 1, it will add them again after it so it becomes 321 321.
Here is the code I need to fix. And sorry for the stupid question I am a beginner with arrays.
I get this error
Index was outside the bounds of the array
My code:
using System;
public class Program
{
public static void Main()
{
int arraylength = int.Parse(Console.ReadLine());
int[] array = new int[arraylength];
for (int i = 0; i < arraylength + 1 / 2; i++)
{
int typed = int.Parse(Console.ReadLine());
array[i] = typed;
if (i == arraylength / 2)
{
for (int a = arraylength + 1 / 2; a < arraylength + 1; a++)
{
array[a] = typed;
}
}
}
}
}
Array indices in C# start at 0 and end at length - 1. You need to remove the + 1 from each of your for loop conditions:
for (int i = 0; i < arraylenght / 2; i++)
and
for (int a = (arraylenght + 1) / 2; a < arraylenght; a++)
I also suggest that you change arraylenght to arraylength. Since you probably autocompleted this every time you used it, the misspelling occurs consistently throughout your code and the compiler is satisfied. However, misspellings make it difficult for humans to read your code.
p.s. Your code doesn't do what you think it does. I suggest you step away from the computer for a moment and write in words what you are trying to accomplish. Describe each step of your solution in as much detail as you can. Then look at how your words match with the code you wrote. You will probably find that you do not need nested loops.

C# Bubble sort error? [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
What's the problem here? I have a block with 2500 random number and i want to sort them with bubble sort. But when I run the program I've got this:
System.IndexOutOfRangeException
error code after this:
if (szamok[i] > szamok[i + 1]).
(Sorry for bad English :/)
int r = 2500;
int seged;
while (r > 1)
{
for (int i = 0; i < 2500; i++)
{
if (szamok[i] > szamok[i + 1])
{
seged = szamok[i + 1];
szamok[i + 1] = szamok[i];
szamok[i] = seged;
}
}
r = r - 1;
}
The error says it: Your index is out of range. You are trying to access an element in your array after the last element in this array.
The line szamok[i] > szamok[i + 1] seems to be the culprit. +1 is one too many.
Try changing you loop so you don't visit the last element but only the second to last:
for (int i = 0; i < (2500-1); i++)

What is Insertion Sort? [duplicate]

This question already has answers here:
Insertion Sorting c#
(3 answers)
Closed 10 years ago.
I am new to programming and just heard about sorting. I went through the basics of sorting and found out that Insertion Sorting is the easiest. But the thing is that I don't get what it is! Can you explain me in detail what is insertion sort and how to implement it. Implementation in c# would be appreciated more.
Any help would be greatly appreciated! :)
Take a loot at Wikipedia
The algorithm for insertion-sort is
int temp, j;
for (int i=1; i < vector.length; i++){
temp = vector[i];
j = i-1;
while (j >= 0 && vector[j] > temp){
vector[j + 1] = vector[j];
j--;
}
vector[j+1] = temp;
}
Insertion sort is more efficient than the alogrithms we have implemented before (Bubble Sort and Selection sort) for sorting a small data set. Insertion sort is mostly used when the list is partially sorted. We assume the 1st element is sorted. Then we check adjacent index for smaller or greater value. If the value is smaller, we insert it in the left side of index[0] which means now smaller value is at index[0] and if it's greater than the original value of index[0] then we get a sorted list of 2 elements. We implement same approach to adjacent elements. Then compare it to previous elements to create a sorted list. So basically - you'll end up with sorted list on the left side of the array and unsorted on the right at one stage. Remember we go back and check if the array is sorted - we do not go forward unless the array behind the concerned element (incl. concerned element) is completely sorted.
Here's the C# implementation of Insertion Sort:
class Program
{
static void Main(string[] args)
{
int i, j;
int[] unsortedarrayed = new int[] { 34, 36, 2, 7, 8, 3, 6, 5 };
for (i = 0; i < unsortedarrayed.Length; i++)
{
Console.WriteLine(unsortedarrayed[i]);
}
int[] sortedarray = InsertionSorted(unsortedarrayed);
for (i = 0; i < sortedarray.Length; i++)
{
Console.WriteLine(sortedarray[i]);
}
Console.Read();
}
public static int[] InsertionSorted(int[] unsortedarrayed)
{
for (int i = 1; i < unsortedarrayed.Length; i++)
{
int temp = unsortedarrayed[i];
int j = i - 1;
while ((j > -1) && (unsortedarrayed[j] > temp))
{
int tempo = unsortedarrayed[j + 1];
unsortedarrayed[j + 1] = unsortedarrayed[j];
unsortedarrayed[j] = tempo;
j = j - 1;
}
}
return unsortedarrayed;
}
}
Source :
For more detail click on following links :
1) Link 1
2) Link 2

Linear Search Problem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My program has no compile errors but the output is incorrect. Example input:
size of array: 5
input numbers: 5 4 3 2 1
//sorted: 1 2 3 4 5
search: 1
output: number 1 found at index 4
the output should be number 1 found at index 0 since the numbers were sorted already. How will I change it to this.
int[] nums = new int[100];
int SizeNum;
bool isNum = false;
private void ExeButton_Click(object sender, EventArgs e)
{
int i, loc, key;
Boolean found = false;
string SizeString = SizeTextBox.Text;
isNum = Int32.TryParse(SizeString, out SizeNum);
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
if (SizeNum == numsInString.Length)
{
Array.Sort(numsInString);
key = int.Parse(SearchTextBox.Text);
ResultText.AppendText("Sorted: ");
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
for (loc = 0; loc < SizeNum; loc++)
{
if (nums[loc] == key)
{
found = true;
break;
}
}
if (found == true)
ResultText.AppendText("Number " + key + " Found At Index [" + loc + "]\n\n");
else
ResultText.AppendText("Number " + key + " Not Found!\n\n");
}
}
}
You're sorting numsInString but then searching nums. nums is being populated before the search, so you're seeing the results of searching the unsorted numbers.
Once you've parsed numsInStrings into nums, you should be working with the latter array only. Make sure that's the one you're sorting and searching through.
In other words, once you replace the current sort call with
Array.Sort(nums);
your code will be fine.
Updated:
You actually need another fix. Right now, you're initializing nums to be an array of size 100. By default, each element will be 0. So even though you put numbers in the first five elements, when you sort the array, you end up with 95 0's, followed by 1 2 3 4 5.
You should delay initializing nums until you've seen how big numsInString is:
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
Now when you sort nums, you'll see only the numbers you entered.
you are sorting the numsInString array, but still searching into the nums array.
for (loc = 0; loc < SizeNum; loc++)
{
if (numsInString[loc] == key)
{
found = true;
break;
}
}
You're parsing numsInString then you're sorting it. (I suspect the sort won't do what you want, either.)
I think you really want to be sorting nums instead:
Array.Sort(nums);
Having said that, there are simpler ways of achieving the end result - such as using IndexOf to find the index of a value in an array.
It's also rather unclear why you've got braces here:
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
...
}
That makes it look like you've got a loop with a body, but it's actually equivalent to:
for (i = 0; i < SizeNum; i++)
{
ResultText.AppendText(" " + numsInString[i]);
}
ResultText.AppendText("\n\n");
{
...
}
... the braces serve no purpose here, and merely harm readability.

Categories