How to make a Jagged Array? - c#

Thinking like a simple array:
Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());
string[] strA = new string[x];
strA[0] = "Hello";
strA[1] = "World";
for(int i = 0;i < x;i++)
{
Console.WriteLine(strA[i]);
}
Now, how can I do it with a double array?
I've already tried this:
Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());
// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];
strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";
for(int i = 0;i < x;i++)
{
for(int j = 0;i < y;i++)
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}
}
If's there's a simpler way of doing this, i'll be happy to learn it.
It's only for knowledge, I'm studying double array for the first time, so have patience please :)
Here's my example:
https://dotnetfiddle.net/PQblXH

You are working with jagged array (i.e. array of array string[][]), not 2D one (which is string[,])
If you want to hardcode:
string[][] strA = new string[][] { // array of array
new string[] {"Hello", "World"}, // 1st line
new string[] {"Thanks", "Guys"}, // 2nd line
};
in case you want to provide x and y:
string[][] strA = Enumerable
.Range(0, y) // y lines
.Select(line => new string[x]) // each line - array of x items
.ToArray();
Finally, if we want to initialize strA without Linq but good all for loop (unlike 2d array, jagged array can contain inner arrays of different lengths):
// strA is array of size "y" os string arrays (i.e. we have "y" lines)
string[][] strA = new string[y][];
// each array within strA
for (int i = 0; i < y; ++i)
strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)
Edit: Let's print out jagged array line after line:
Good old for loops
for (int i = 0; i < strA.Length; ++i) {
Console.WriteLine();
// please, note that each line can have its own length
string[] line = strA[i];
for (int j = 0; j < line.Length; ++j) {
Console.Write(line[j]); // or strA[i][j]
Console.Write(' '); // delimiter, let it be space
}
}
Compact code:
Console.Write(string.Join(Environment.newLine, strA
.Select(line => string.Join(" ", line))));

You're using a jagged array instead of a multidimensional one. Simply use [,] instead of [][]. You can then use it with new string[x, y].

First you need to clarify thing in your head before writing code.
I will recommend writing in simple phrase what you want to do. The code in your fiddle go into every direction. I will address the code in the fiddle and not your questionas you have typo error and other issue that where not present in the fiddle while the fiddle has error that the question do not have.
To simplify the problem lets use clear understandable names. The 2d array will be an table, with rows and columns.
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns:");
var y = int.Parse(Console.ReadLine());
var table = new string[x, y];
You need to to declare your table before knowing its size.
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row, col] = Console.ReadLine();
}
}
table.GetLength(0) is equivalent to X, and table.GetLength(1) is equivalent to Y, and can be replace.
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write(table[row, col]);
}
Console.Write("\n");
}
For a 3x3 table with 00X, 0X0, X00 as inputs the result is
00X
0X0
X00
It works. You separate each cell when we display by simply adding a comma or a space.
Fiddle
And for Jagged Array:
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
var table = new string[x][];
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
Console.WriteLine($"Enter of the line n°{row}");
var lineSize = int.Parse(Console.ReadLine());
table[row] = new string[lineSize];
for (int col = 0; col < table[row].Length; col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row][col] = Console.ReadLine();
}
Console.Write("\n");
}
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.Length; row++)
{
for (int col = 0; col < table[row].Length; col++)
{
Console.Write(table[row][col]);
}
Console.Write("\n");
}

Wrong variable in use:
for(int j = 0;i < y;i++) <- Should be j
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}

Related

how to print the row of a matrix(multi-dimensional array) in a new line

I have a multi-dimensional array in C#, I have assigned the indices of the matrices by capturing input from a user, I am trying to implement a conditional structure that will let me print the rows of my matrix each on a separate line, for example if my array is A and A has a dimension of 3 by 3 then the code prints the first three elements on the first line, the next three elements on the next line and so on and so forth. I am trying to achieve this because it will be easier to understand the structure as a normal matrix and also build an entire matrix class with miscallenous operations.
Code
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
How do I modify my code so that if the array has 9 elements and its a square matrix then each row with three elements are printed on a single line.
I would use something like this for the output:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
When the inner loop is done, that means one row has been completely printed. So that's the only time the newline is needed. (n passes of the outer loop ==> n newlines printed).

I need to assign string to array columns after split method c#

I have a multidimensional array that takes lines based on user input like(n lines/4col )
and I have a string of 4 numbers in a line separated by 1 space: 10.00 20.00 30.00 40.00. I need to assign each number to a column in 1 line. The code that I have until now:
int storeNumbers = int.Parse(Console.ReadLine());
string[,] storesemesterProfit = new string[storeNumbers, 4];
for(int m=0; m<storeNumbers; m++)
{
for(int n=0; n < 4; n++)
{
string inputData = Console.ReadLine()
string [] numb = inputData.Split(' ');
storesemesterProfit[m, n] = numb ; // i need help here
You might be looking for
int storeNumbers = int.Parse(Console.ReadLine());
var storesemesterProfit = new decimal[storeNumbers, 4];
for (var m = 0; m < storeNumbers; m++)
{
string inputData = Console.ReadLine();
var numb = inputData.Split(' ');
for (int n = 0; n < Math.Min(4, numb.Length); n++)
storesemesterProfit[m, n] = decimal.Parse(numb[n]);
}
Fair warning. This will likely explode if the user enters some bad data. I suggest taking a look at TryParse Methods

Multi-dimensional foreach loop

How can I properly do so that a check is performed for each string?
My code looks like :
string[,] screeny_baza = new string[300, 300];
for (int i = 0; i < 299; i++)
{
try
{
string nazwa_screna_pokolei = screeny_baza[0,i]
}
catch { };
}
As i see i want to do just it one by one. Is it possible to do it faster omitting values ​​that do not exist or have not been declared? They are just null i think.
I have dimension that looks like to 300/300 .
X0 X1 X2
Y0 00 10 20
Y1 01 11 21
Y2 02 12 22
And want to save just string to each of dimesnion for example
string [00] = "bird";
string [01] = "bird2";
and later need to get this values in loop ( omitting values ​​that do not exist or have not been declared)
Thanks for help.
I don't know about foreach loops on multi dimensional arrays but you can always do this:
string[,] screeny_baza = new string[300, 300];
for (int x = 0; x < screeny_baza.GetLength(0); x++)
{
for (int y = 0; y < screeny_baza.GetLength(1); y++)
{
try
{
string nazwa_screna_pokolei = string.empty;
if (screeny_baza[x, y] != null)
nazwa_screna_pokolei = screeny_baza[x, y];
}
catch { };
}
}
You can foreach on a 2d array. You can even LinQ Where to filter it.
var table = new string[20, 20];
table[0, 0] = "Foo";
table[0, 1] = "Bar";
foreach (var value in table.Cast<string>().Where(x =>!string.IsNullOrEmpty(x))) {
Console.WriteLine(value);
}
Actually your try-catch block will not raise any exception because when you construct the array:
string[,] screeny_baza = new string[300, 300];
you can always index it as long as the indexes are in range; so the statement:
string nazwa_screna_pokolei = screeny_baza[0,i];
will execute without error. Just nazwa_screna_pokolei will be null;
Also if speed is concerned, a nested for-loop is much faster than LinQ. at least for this simple check. for example:
var list = screeny_baza.Cast<string>().Where(x => !string.IsNullOrEmpty(x)).ToList();
will take about 10 milliseconds, but
for (int i = 0; i < 300; i++)
{
for (int j = 0; j < 300; j++)
{
if (string.IsNullOrEmpty(screeny_baza[i,j]))
{
continue;
}
list.Add(screeny_baza[i, j]);
}
}
will take only 1 millisecond.
For storing you would use row and column indices like:
screeny_baza[0,0] = "bird";
screeny_baza[0,1] = "bird";
For looping the values you use GetLength (though you know the dimensions as constant, this is a more flexible way):
for (int row = 0; row < screeny_baza.GetLength(0); row++) {
for (int col = 0; col < screeny_baza.GetLength(1); col++) {
if (!string.IsNullOrEmpty(screeny_baza[row,col])) // if there is a value
Console.WriteLine($"Value at {row},{col} is {screeny_baza[row,col]}");
}
}
My simple helper for such cases
private static void forEachCell(int size, Action<int, int> action)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
action(j, i);
}
}
}
It can be modified to use different sizes.
Usage example:
double totalProbability = 0;
forEachCell(chessboardSize, (row, col) =>
totalProbability += boardSnapshots[movesAmount][row, col]);
return totalProbability;

C# foreach loop take values from outer loop to inner loop

I have the below code.
int[] a = new int[] { 8, 9 };
for(int i=0;i<n;i++)
{
print i;
int z;
//during first iteration
z=8;
during second iteration
z=9;
}
Output should be something like this.
during first iteration i=0 and z=8
during second iteration i=1 and z=9
array a contains 2 elements. N and number of elements in array a will be always same. next my for loop will execute. during first iteration want z value should be 8(first element of array ) and second iteration my z value should be 9. I want to map 1st element of integer array to first iteration of for loop and so on.
try
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
int z = a[i]; // this line will get value from a one by one, 0, 1, 2, 3 and so on...
}
Edit 1 -
After seeing the comments on the other answer, the array 'a' turns out is a dynamic array which have size n (which is 2)
the revised edition:
int n = 2;
int[] a = new int[n];
string input = null;
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
input = Console.ReadLine();
try {
a[i] = int.Parse(input);
Console.WriteLine(string.Format(
"You have inputted {0} for the {1} element",
input, i
));
} catch { Console.WriteLine("Non integer input"); i -= 1; }
}
you can try this
int [] a = {8,9};
for(int i=0; i< a.Length; i++)
{
int z = a[i]; //for taking value from array at the specific ith position
Console.WriteLine("i: " + i + " z:" + z);
}
try this
List<int> a = new List<int>();
int n = 2; // you can change it according to your need
for (int i = 0; i < n; i++)
{
string str = Console.ReadLine(); // make sure you enter an integer and conver it
int z = int.Parse(str);
a.Add(z);
}
foreach (int k in a)
{
Console.WriteLine(k);
}

cannot apply indexing with [] to an express of type 'method group, (how to print array)

i have array that call nums, it contain int var.
the array is 2d -
int[,] nums = new int[lines, row];
i need to print each line in the array in other line.
when i try to print to array like this:
for (int i = 0; i < lines; i++)
for (int j = 0; j < 46; j++)
Console.Write(nums[i,j]);
** when i using the above syntax i dont get an error in visual studio, but when i run the program, i got error in this line - Console.Write(nums[i,j]);.
error - system.IndeOutOfRangeException.
i got the error , i try to change the syntax to this:
for (int i = 0; i < lines; i++)
for (int j = 0; j < 46; j++)
Console.Write(nums[i][j]);
the error: "wrong number of indices inside []; expected 2"
and:
for (int i = 0; i < lines; i++)
for (int j = 0; j < 46; j++)
Console.Write(nums[i][j].tostring());
update
i am so stupid... i write 46(number in my program) instead of 6(numbers in each row) thats whey is was out of range.
ty for all, and i am sry to open a question with such bad problem...
TY!
If lines and row are positive integer values, say, int lines = 5; int row = 7; you can print out your table like this:
int[,] nums = new int[lines, row]; // <- Multidimensional (2 in this case) array, not an array of array which is nums[][]
//TODO: fill nums with values, otherwise nums will be all zeros
for (int i = 0; i < lines; i++) {
Console.WriteLine(); // <- let's start each array's line with a new line
for (int j = 0; j < row; j++) { // <- What the magic number "46" is? "row" should be here...
Console.Write(nums[i, j]); // <- nums[i, j].ToString() doesn't spoil the output
if (j > 0) // <- let's separate values by spaces "1 2 3 4" instead of "1234"
Console.Write(" ");
}
}
You are dealing with 2 different types of arrays
int[,] nums = new int[lines, row];
is a Multi-Dimensional Array. Elements of the array can be accessed using nums[x,y].
When you use nums[x][y] you are dealing with an array of arrays.
You cannot use array of arrays syntax with a multi-dimensional array.
You might try What are the differences between Multidimensional array and Array of Arrays in C#? for details.

Categories