Maff
Maff

Reputation: 1032

Populate 2Dimensional Array

I am trying to write some logic which allows me to store values into a 2 dimensional array. Within the function below, I would like to store the current coins[i] value, with the corresponding coin variable as a pair. However, I am not exactly sure how I can this can be done. Reason being is that I would like to loop through the array once it has been populated and print out the current coins[i] value along with the corresponding coin variable which indicates the amount of times used to dispense change.

Function:

int counter = 0;
int coin;
for (int i = 0; i < coins.Length; i++)
{
    coin = Math.Min(quantities[i], (int)(change / coins[i]));
    counter += coin;
    change -= coin * coins[i];
    // want to store [coins[i], coin] in an 2Darray
}
Console.WriteLine("Number of coins = {0}", counter);

If there is another way that this can be done, please be sure to provide suggestions. Bare in mind I cannot use anything from the Collection classes. All answers are appreciated.

Upvotes: 1

Views: 128

Answers (3)

Codor
Codor

Reputation: 17605

As the discussion might be a bit hard to follow - is the code below what you are looking for?

// suppose the definition of array 'coins' is somewhere else

int counter = 0;
int coin;

int[] change_given = new int[coins.Length]; // will be the same length as 'coins'

for (int i = 0; i < coins.Length; i++)
{
    coin = Math.Min(quantities[i], (int)(change / coins[i]));
    counter += coin;
    change -= coin * coins[i];
    // want to store [coins[i], coin] in an 2Darray
    change_given[i] = coin;
}

for (int j = 0; j < change_given.Length; j++)
{
     Console.WriteLine("Number of coins of type {0} returned: {1}", j, change_given[j]);
}

Upvotes: 1

Codor
Codor

Reputation: 17605

As described here, a two-dimensional array can be defined by, for instance,

int[,] array = new int[4, 2];

and accessed by

array[i][j] = SomeValue;

in fact it is addressed the same way as in your commented-out code.

Upvotes: 0

abdoulcool
abdoulcool

Reputation: 116

You can do this by using a 2 dimentional array having coins.Length as the length and 2 as the width of the array.

int[,] x = new int[coins.Length, 2];
for (int i = 0; i < coins.Length; i++)
{
        ... your code    
        x[i, 0] = coin;
        x[i, 1] = coins[i];
}

Upvotes: 0

Related Questions