Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a 3x3 matrix with user input numbers C#

Tags:

c#

im trying to create a 3x3 matrix in c# language, i know how to create the matrix but i need help for user input numbers. I hope someone can help me thank you for that.

like image 685
user2853957 Avatar asked Oct 07 '13 09:10

user2853957


2 Answers

I will add a while loop and use double.TryParse to validate user's input. Usin BWHazel's code:

const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;

double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];

for (int i = 0; i < MATRIX_ROWS; i++)
{
    for (int j = 0; j < MATRIX_COLUMNS; j++)
    {
        double input;
        Console.Write("Enter value for ({0},{1}): ", i, j);
        while (!double.TryParse(Console.ReadLine(), out input)
        {
            Console.Write("Enter correct value for ({0},{1}): ", i, j);
        }
        matrix[i,j] = input
    }
}

To get the totals for all rows you can use following snippet:

for (int i = 0; i < MATRIX_ROWS; i++) 
{
    // The some for each row
    double sum = 0.0;
    for (int j = 0; j < MATRIX_COLUMNS; j++)
    {
        sum += matrix[i,j];
    }
    Console.WriteLine(string.format("The sum for row {0} is: {1}", i, sum));
}
like image 188
iTURTEV Avatar answered Oct 11 '22 14:10

iTURTEV


If you are using the command-line, something like this should work:

const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;

double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];

for (int i = 0; i < MATRIX_ROWS; i++)
{
    for (int j = 0; j < MATRIX_COLUMNS; j++)
    {
        Console.Write("Enter value for ({0},{1}): ", i, j);
        matrix[i,j] = double.Parse(Console.ReadLine());
    }
}

This assumes you are using double for the values. The .Parse() method is available for all .NET numeric types including int.

like image 26
BWHazel Avatar answered Oct 11 '22 13:10

BWHazel