C# System.IndexOutOfRangeException but program is working - c#

This program generates random 2d array and calculates maximum in every line. I do have right results, but IndexOutOfRangeException popping up if number of columns does not equals to the number of lines.
Random r = new Random();
int x,y;
Console.WriteLine("lines");
x = int.Parse(Console.ReadLine());
Console.WriteLine("columns");
y = int.Parse(Console.ReadLine());
if ((x < 1) || (y < 1))
{
Console.WriteLine("Error");
Console.ReadLine();
}
else
{
int[,] array1 = new int[x, y];
int[] array2 = new int[y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
array1[i, j] = r.Next(0, 51);
Console.Write(array1[i, j] + " ");
}
Console.WriteLine();
}
for (int j = 0; j < y; j++)
{
int max = array1[j, 0];
for (int i = 1; i < x; i++)
{
if (array1[j, i] > max)
{
max = (array1[j, i]);
}
else
{
}
}
array2[j] = max;
Console.WriteLine();
Console.Write(array2[j]);
}
Console.ReadLine();
}

On your second pass through the data (the one where you go by lines first rather than by columns), this:
if (array1[j, i] > max)
{
max = (array1[j, i]);
}
should look like this:
if (array1[i, j] > max)
{
max = (array1[i, j]);
}
Changing the order in which you process rows and columns doesn't change the dimensions of the array.
Edit: per #csharpfolk's comment, this line also needs fixing:
int max = array1[j, 0];
probably to:
int max = array1[0, j];

Related

The Snake in the 2D array

I have to write a program that creates a two dimensional array and fills it like a snake. Here is the task itself:
Blockquote write a program that creates a two-dimensional numeric array and this array is filled with a "snake": first the first row (from left to right), then the last column (from top to bottom), the last row (from right to left), the first column (from bottom to top), the second row ( left to right), etc.
I tried to write something, but bugs constantly appear. Please help to shorten this code and make it correct.
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int len = rand.Next(5, 20);
int wid = rand.Next(5, 20);
int[,] arr = new int[len, wid];
int num = 10;
int line = 0;
int line2 = len;
int col = wid - 1;
int col2 = 0;
for (int i = 0; i <= (len > wid ? len : wid); i++)
{
for (int k = 0; k < wid; k++, num++)
{
arr[line, k] = num;
}
line++;
for (int k = 0; k < len; k++, num++)
{
arr[k, col] = num;
}
col++;
for (int k = (wid - 1); k >= 0; k--, num++)
{
arr[line2, k] = num;
}
line2++;
for (int k = 0; k < (len - 1); k++, num++)
{
arr[k, col2] = num;
}
col2++;
}
for (int i = 0; i <= len; i++)
for (int q = 0; q <= wid; q++)
{
Console.WriteLine(arr[i, q] + " ");
}
}
}

Improved Selection Sort Out of Bounds Error

I have a method that is an "Improved version of Selection Sort". However, the code is not running as " temp[x] = 0;" this line gives an out of bounds of the array error. I do not want to use an ArrayList. How would I change this line to be in bounds of the array?
public static void ImprovedSelectionSort(int[] Array)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int[] temp = new int[Array.Length];
for (int x = 1; x <= Array.Length; x++)
{
//OtherList.Add(0); -- what I want to do
temp[x] = 0;
}
int n = Array.Length;
int i = 0;
while (i < n)
{
int rear = 0;
int curMax = Array[i];
temp[rear] = i;
int j = i + 1;
while (j < n)
{
if (curMax < Array[j])
{
curMax = Array[j];
rear = -1;
}
if (curMax == Array[j])
{
rear = rear + 1;
temp[rear] = j;
}
j++;
}
int front = 0;
int p = Array[temp[front]];
while (front <= rear)
{
int temporary = p;
Array[temp[front]] = Array[i];
Array[i] = temporary;
i++;
front += 1;
}
}
for (int x = 1; x <= Array.Length; x++)
This is most likely the issue. The last index in an array is the length minus 1 (so, a 52-card deck goes from 0..51). Changing the "x <= Array.Length" component to "x < Array.Length" should fix the issue.
Change the <= to < in the for loop. This is a common mistake among novice devs, and not something you should sweat. But it's a good thing to keep in mind for the future.

Creating mutidimensional array consisting of asterisks

I am new to programming and I want my program to run a table consisting of stars(asterisks). E.g. table 4x3 has 4x3 stars. But my initial problem is that I do not know how to implement a multidimensional array in such a way that I just need to change the initial value of rows and columns in order to create more or less stars.
So: here is my code at the moment:
using System;
namespace ConsoleApplication1
{
class Multidimensional_array
{
static void Main(string[] args)
{
int arrayRows = 4;
int arrayCols = 3;
int[,] arrayTimes;
arrayTimes = new int [arrayRows, arrayCols];
//String star = "*";
for( int i = 0; i <= arrayRows; i++) {
for( int j = 0; j <= arrayCols; j++) {
//Console.WriteLine("*");
//arrayTimes[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.ReadLine();
}
}
}
So I just want that if I change the int arrayRows to 5 and int arrayCols to 5 then I receive a star table of 5x5. T
I think you're very close, you're just using the wrong data type for your array, haven't assigned the * to each position in said array, and your current code would give you an ArrayIndexOutOfBounds exception. You may have 4 rows and 3 columns, but array indices are zero-based, meaning when you access positions 1, 2, 3, etc. you use an index of 0, 1, 2, etc. respectively.
So, since you want to store the text "*", you should use a char[,] or a string[,] for your multi-dimensional array. I've chosen char[,] for this:
int arrayRows = 4;
int arrayCols = 3;
char[,] arrayTimes = new char[arrayRows, arrayCols];
const char star = '*';
// Set it up
for (int i = 0; i <= arrayRows - 1; i++)
{
for (int j = 0; j <= arrayCols - 1; j++)
{
arrayTimes[i, j] = star;
}
}
// Print it out
for (int i = 0; i <= arrayRows - 1; i++)
{
for (int j = 0; j <= arrayCols - 1; j++)
{
Console.Write(arrayTimes[i, j]);
}
Console.WriteLine();
}
Working ideone sample
Simple solution
static void Main(string[] args)
{
// Get the number of rows
Console.WriteLine("Enter the number of rows:");
int arrayRows = Convert.ToInt32(Console.ReadLine());
// Get the number of columns
Console.WriteLine("Enter the number of columns:");
int arrayCols = Convert.ToInt32(Console.ReadLine());
// For each item in the row
for (int i = 0; i < arrayRows; i++)
{
// For each item in the column
for (int j = 0; j < arrayCols; j++)
{
// Show a star
Console.Write("*");
}
// End the line
Console.WriteLine("");
}
// Read the line to stop the app from closing
Console.ReadLine();
}
If you want to store the stars
static void Main(string[] args)
{
// Get the number of rows
Console.WriteLine("Enter the number of rows:");
int arrayRows = Convert.ToInt32(Console.ReadLine());
// Get the number of columns
Console.WriteLine("Enter the number of columns:");
int arrayCols = Convert.ToInt32(Console.ReadLine());
// Create an array
char[,] arrayTimes = new char[arrayRows, arrayCols];
char star = '*';
// For each item in the row
for (int i = 0; i < arrayRows; i++)
{
// For each item in the column
for (int j = 0; j < arrayCols; j++)
{
// Show a star
arrayTimes[i, j] = star;
}
}
// Read the line to stop the app from closing
Console.ReadLine();
}
This do what you want,
int arrayRows = 2;
int arrayCols = 2;
char[,] arrayTimes;
arrayTimes = new char[arrayRows, arrayCols];
//String star = "*";
for (int i = 0; i < arrayRows; i++)
{
for (int j = 0; j < arrayCols; j++)
{
arrayTimes[i, j] = '*';
Console.Write("{0}",arrayTimes[i, j]);
}
Console.WriteLine();
}
Console.ReadKey();

Getting numbers from a matrix

Hi my problem is I can't get the numbers with more than 2 digits from this matrix if anyone can help I would appriciate it here i my code :
Console.Write("x: ");
int x = int.Parse(Console.ReadLine());
Console.Write("y: ");
int y = int.Parse(Console.ReadLine());
int[,] arr = new int[x, y];
int[,] arr2 = new int[x, y];
Random rand = new Random();
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
int randNUm = rand.Next(0, 20);
arr[i, j] = randNUm;
Console.Write(arr[i, j] + " ");
if (arr[i, j] >= 10)
{
arr2[i,j] = arr[i,j]
}
}
}
Actually you have done your job, all it remains is to display the results. If
the task specifies that the printing must be done in 2 steps as you imply,
try:
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
int randNUm = rand.Next(0, 20);
arr[i, j] = randNUm;
Console.Write(arr[i, j] + " ");
if (arr[i, j] >= 10)
{
arr2[i,j] = arr[i,j]
}
}
}
Console.WriteLine("---Proceeding to 2 digit numbers---");
for (int i = 0; i < arr2.GetLength(0); i++)
{
for (int j = 0; j < arr2.GetLength(1); j++)
{
Console.Write(arr2[i, j] + " ");
}
}
EDIT : Consider what Henk comments and try to optimise your solution.

Creating a 3x3 Matrix and ordering numbers in a vortex from smaller to bigger

i would like to create a 3x3 matrix with input numbers and then orders number from smaller to bigger and place it in the matrix like a vortex like : 1,2,3,4,5,6,7,8,9 and place number 1 to 0.0 position,2 to 0.1, 3 to 0.2, 4 to 1.2, 5 to 2.2, 6 to 2.1, 7 to 2.0, 8 to 1.0 and 9 to 1.1.
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
List<int> l = new List<int>(l);
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS * MATRIX_COLUMNS; ++i)
{
int input;
Console.Write("Enter value");
while (!int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
l.Add(input);
}
l.Sort();
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
matrix[i, j] = l[i * 3 + j];
}
I start like that to get input numbers and i would like help for the second part.
this will present you with the "vortex like" result for the matrix:
List<int> nums = new List<int>();
double[,] matrix = new double[3,3];
for (int i = 0; i < 9; ++i)
{
double input;
Console.Write("Enter value");
while (!double.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
nums.Add(int.Parse(input.ToString()));
}
nums.Sort();
int block = 0;
int[] order = new int[] { 0, 1, 2, 2, 2, 1, 0, 0, 1 };
for (int i = 0 ; i < order.Length; i++)
{
switch (block)
{
case 0:
matrix[block, order[i]] = nums[i];
if (i == 2)
block = 1;
break;
case 1:
if (i < order.Length - 3)
{
matrix[block, order[i]] = nums[i];
block = 2;
}
else
matrix[block, order[i]] = nums[i];
break;
case 2:
if(i == order.Length - 3)
{
matrix[block, order[i]] = nums[i];
block = 1;
}
else
matrix[block, order[i]] = nums[i];
break;
}
}
Console.WriteLine("The Resulting Matrix is:");
for (int row = 0, col = 0; row < 3; row++)
{
Console.WriteLine("row " + row + ": {0} - {1} - {2}", matrix[row, col], matrix[row, col + 1], matrix[row, col + 2]);
col = 0;
}
EDIT:now it displays the results.
As I see it - you can declare a List<int> l somewhere at the beginning, read the whole data by l.Add(x); then perform l.Sort() and after the data is sorted - populate your matrix. Let me know if you have further questions.
So you will get something like
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
List<int> l = new List<int>();
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS * MATRIX_COLUMNS; ++i)
{
double input;
Console.Write("Enter value");
while (!double.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
l.Add(input);
}
l.Sort();
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
matrix[i, j] = l[i*3 + j];
}
}

Categories

Resources