Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

usage of multidimensional arrays

Status
Not open for further replies.

malola123

Technical User
Feb 16, 2007
17
CA
Hey,

I was practicing some c# concepts while i found this weird thing happening. I am basically creating a simple two dimensional array with 3 rows and 2 columns. Here is the code.

using System;

class Array
{
public static void Main()
{
int[,] myArray =
{

{ 2, 3 },
{ 4, 5 },
{ 6, 7 }
};
int x;
int y;

for (x = 0; x < 3; x++)
for (y = 0; y < 2; y++)
Console.WriteLine( myArray[x, y] + " ");

Console.WriteLine();

}
}

Everything seems fine, and once I debug it, there are no build errors. However, when the console results are shown the follwing is displayed:

2
3
4
5
6
7

It do not want this type of display. My preference is:

2,3
4,5
6,7

Can anyone show what im doing wrong. Please and thanks!!
 
I don't have access to the tools to check it atm, but I think what you want to do is this:

Code:
for (x = 0; x < 3; x++)
     Console.WriteLine( myArray[0, x] + ", " + myArray[1,x]);

I imagine you will have to convert the integers to strings.

Hope this helps,

Alex

Ignorance of certain subjects is a great part of wisdom
 
Console.WriteLine( myArray[x, y] + " ");

This line is causing only one number to be displayed on a line.

try using Console.Write() instead.
 
This will give you what you want

int[,] myArray =
{
{2,3},
{4,5},
{6,7}
};
int x;
int y;

for (x = 0; x < 3; x++)
{
string line = string.Empty;

for (y = 0; y < 2; y++)
{
line += myArray[x, y].ToString() + ",";
}

line = line.Substring(0, line.Length - 1);
Console.WriteLine(line);
}

The problem was that you were just getting the value of the array originally at the spot and making it its own line. You need to construct a line based on the output format you wanted to get. This may not be ideal or optimized, but it does work and should give you the idea.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top