Freakenknight Freakenknight - 1 month ago 5
C# Question

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

Answer

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();
}
Comments