Inserting into Array (C#) - 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.

Related

C# Index out of bounds

I am trying to make a linear search where the user inputs a selection of numbers and then they input a random number and the program shows if it is in the list or not.
int[] list = new int[10];
bool found = false;
for (int i = 0; i < 12;)
{
Console.WriteLine("Enter number to be stored.");
list[i] =Convert.ToInt16(Console.ReadLine());
i++;
}
Console.WriteLine("Enter number you want to find.");
int n1 = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i <= 10;)
{
if (list[i] == n1)
{
Console.WriteLine(n1 + " is in the list.");
found = true;
Console.ReadKey();
}
else i++;
}
if (found == false)
{
Console.WriteLine("Element not in this list.");
}
Console.ReadKey();
I am pretty sure that the problem lies in this snippet of code.
int[] list = new int[10];
bool found = false;
for (int i = 0; i < 12;)
{
Console.WriteLine("Enter number to be stored.");
list[i] =Convert.ToInt16(Console.ReadLine());
i++;
}
An array beings with 0 so there are 11 element spaces right?
So when i run it, i go past entering the 10th number and when i enter the 11th, it breaks and says
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
Firstly I'd recommend you read up on for loops and arrays in C#.
Secondly you don't want to hardcode the length in the for loop - let the framework do it for you using list.Length. You're seeing the crash because you're trying to assign a value to your array, but the index within your array doesn't exist.
int[] list = new int[10];
bool found = false;
for (int i = 0; i < list.Length; i++)
{
// Do work with list[i]
}
When you say int[10]; you tell it to have 10 entries. They are counting from zero, yes, but that just means that your array has the indices 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Your loop goes from i = 0 up to i = 11 before it stops because it's no longer smaller than twelve. But the index for the array can at most be 9.
If you set a breakpoint, you should be able to look at the array contents in a debugger. This way, you could also test such things yourself.
It should be i < 10 or i <= 9 if your array only holds 10 objects. The 10 indices will be 0-9.

In my class i have to creating a method to find multiple maximum numbers in an array C#

In my class i have to create a method that will find multiple maximum numbers within an array. the user will input how many maximum numbers they are wanting and then the code should display all those numbers. if i select 2 this code will show me the 2 maximum numbers but if im wanting more it just doesnt work. i was trying to search the array for the maximum number and then have it display the outcome and then change that element to 0 and than repeat the loop until it hits that number (userinput). im soo frustrated can someone help me please
public static int FindingMaxNum(int[] arr, int max)
{
int userinput;
Console.Write("Enter the number of maximum values: ");
userinput = Convert.ToInt32(Console.Read());
int i = 0;
int c = 0;
for (i = 0; i < arr.Length; i++)
{
if (arr[i] >= max)
{
max = arr[i];
c++;
while (c <= userinput)
{
Console.WriteLine(max);
arr[i] = 0;
break;
}
}
}
return -1;
}
If I understand correctly, you want to get some number of items from an array whose values are greater than all the others in the array.
If so, something like this modified version of your method may do the trick:
public static void WriteMaxNum(int[] arr)
{
if (arr == null)
{
Console.WriteLine("The array is null");
return;
}
if (arr.Length == 0)
{
Console.WriteLine("The array is empty");
return;
}
int count = arr.Length;
int numMaxValues;
// Get number of max values to return from user
do
{
Console.Write("Enter the number of maximum values (1 - {0}): ", count);
} while (!int.TryParse(Console.ReadLine(), out numMaxValues) ||
numMaxValues < 1 ||
numMaxValues > count);
// Output the max values
Console.Write("The {0} max values are: ", numMaxValues);
Console.WriteLine(string.Join(", ", arr.OrderByDescending(i => i).Take(numMaxValues)));
}
Usage
static void Main(string[] args)
{
var myArray = new[] { 1, 9, 4, 8, 2, 5, 0, 7, 6, 3 };
WriteMaxNum(myArray);
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Simple solution with average complexity O(nlogn):
Sort the array first then print the last N nos.
int[] arr = new int[]{-5,-69,1250,24,-96,32578,11,124};
Array.Sort(arr);
int n=3;
for(int i=arr.Length-1;i>=0 && n>0 ;--i){
n--;
Console.WriteLine(arr[i]);
}
Now coming to your code, there are multiple problems. First there is no need to take 'max' as parameter in your function. Second you are looping only arr.Length times once. There should be nested loop, outer one of which has to run userInput times and inner on has to iterate over all the values. Third you should initialize to extracted value position to minimum value so that the method works for negative numbers too.
Refined code:
for(int i=0;i<userinput;++i){
int max = int.MinValue,pos=-1;
for(int j=0;j<arr.Length;++j){
if(max<arr[j]){
pos = j;
max = arr[j];
}
}
arr[pos] = int.MinValue;
Console.Write(max+",");
}

Convert "int" into "char" inside char array

I am trying to do string manipulation. Here's my C# code :
static void Main(string[] args)
{
string input;
string output;
int length;
Console.WriteLine("input = ");
input = Console.ReadLine();
length = input.Length;
if ((input != "") || (length != 0))
{
Random randem = new Random();
int i = -1; //because I do not want the first number to be replaced by the random number
char[] characters = input.ToCharArray();
while (i < length)
{
int num = randem.Next(0, 9);
char num1 = Convert.ToChar(num);
i = i + 2; //so that every next character will be replaced by random number.. :D
characters[i] = num1; //*error* here
}
output = new string(characters);
Console.WriteLine(output);
}
For example:
User input : "i_love_to_eat_fish"
Desired output : "i2l4v1_9o5e8t7f8s2"
notice that the only unchanged character in
the char[] characters is : "i l v _ o e t f s". (desired output from the program)
I've already tried using this code, but still,
keep getting error at characters[i] = num1;
Am I on the right track?
I'm guessing the error you get is IndexOutOfRangeException this is because of the i = i + 2;. The while makes sure that i is less than length, but then adding 2 could result in it being more. Just add a check that it isn't beyond the length.
i = i + 2;
if(i < length)
characters[i] = num1;
Or just change to a for loop.
Random randem = new Random();
char[] characters = input.ToCharArray();
for(int i = 1; i < length; i += 2)
{
int num = randem.Next(1, 10); // max value is exclusive
char num1 = num.ToString()[0];
characters[i] = num1;
}
output = new string(characters);
Console.WriteLine(output);
Also as Shar1er80 points out you're currently converting the digit to the char that has the same ASCII value, and not the the actual characters that represent the digit. The digits 0-9 are represented by the the values 48-57. You can change the call to Random.Next to be:
int num = randem.Next(48, 58); // The upper bound is exclusive, not inclusive
char num1 = (char)num;
Or as Shar1er80 does it
int num = randem.Next(0,10) // Assumming you want digits 0-9
char num1 = num.ToString[0];
Also note that the max value for Random.Next is exclusive, so if you want to include the possibility of using a 9 you have to use an upper bound that is 1 greater than the greatest value you want.
Whenever you reach i = 17 you add 2 to i . That makes i = 19 with length of input equal to 18 that causes out of range exception.
The error you are getting is IndexOutOfTheRangeException, which explains everthing in itself.
It means that index you are feeding to array in the loop is going beyond its length-1 (as arrays have 0-based indexing)
So when you do i+2, you need to check if i+2 is not exceeding i.length-1 at any point of time; which does in your loop.
In general just check if you are supplying indexes between 0 and Array.Length-1
its because you start at index -1, and characters doesn't contain an index of -1.
EDIT: Sorry no the corrct answer is it must be while(i < length - 2)
Change this line
char num1 = Convert.ToChar(num);
To
char num1 = num.ToString()[0];
Then... Put
characters[i] = num1;
In an if block
if (i < length)
characters[i] = num1;

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!

How to get the middle element in array?

How can we get the middle element in an array?
Example code:
string[] source = txtInput.Text.Split(',');
int[] nums = new int[input.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first=nums[0];
int mid=///how is it?
Like this:
int mid = nums[nums.Length/2];
You take the size of the array (nums.Length), divide by two to get the index in the middle and use that index.
int mid = nums[nums.Length / 2];
Since it is all ints the number will be rounded down if Length is odd.
mid = input.Lenght/2
Get the middle index and then return the element at that middle index:
int [] arr = {1,2,3,4,5,6,7}
int middIndex = arr.Length / 2;
Console.WriteLine(arr[middIndex]);
the total number of elements devided by 2 gives the middle element:
int mid = nums[Convert.ToInt32(num.Count /2)];

Categories

Resources