I made a program that calculates multiplication of matrices in c#. Is it possible to show the result like this?
(Matrix1) * (Matrix2) = (Result)
My code :
using System;
namespace MatrixMultiplication;
{
class MainClass
{
static void ShowMatrix(int [,] m){
for (int i = 0; i < m.GetLength(0); i++) {
for (int j = 0; j < m.GetLength(1); j++) {
Console.Write(m[i,j]+" ");
}
Console.WriteLine ();
}
}
static int[,] MultiplyMatrices(int [,] a , int [,] b){
int[,] result = new int[a.GetLength(0),a.GetLength(1)];
for (int i = 0; i < a.GetLength(0);i++) {
for (int j = 0; j < a.GetLength(0); j++) {
for (int k = 0; k < a.GetLength(1); k++) {
result [i, k] += a [i, j] * b [j, k];
}
}
}
return result;
}
public static void Main (string[] args)
{
int rows,columns;
Console.WriteLine ("Rows : ");
rows = Convert.ToInt32 (Console.ReadLine());
Console.WriteLine ("Columns : ");
columns = Convert.ToInt32(Console.ReadLine());
int [,] lhsm = new int[rows,columns];
int [,] rhsm = new int[rows,columns];
int [,] result = new int[rows,columns];
Console.WriteLine ("Enter Elements of the First matrix : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Console.WriteLine ("F[{0}][{1}] : ",i,j);
lhsm [i,j] = Convert.ToInt32 (Console.ReadLine ());
}
}
Console.WriteLine ("Enter Elements of the Second matrix : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Console.WriteLine ("L[{0}][{1}] : ",i,j);
rhsm [i,j] = Convert.ToInt32 (Console.ReadLine ());
}
}
result = MultiplyMatrices (lhsm, rhsm);
Console.Clear ();
Console.WriteLine ("Matrix 1 : ");
ShowMatrix (rhsm);
Console.WriteLine ("Matrix 2 : ");
ShowMatrix (lhsm);
Console.WriteLine ("Result : ");
ShowMatrix (result);
}
}
}
One way to do this using SetCursorPosition would be to modify your ShowMatrix method to first store the starting position of the cursor, and then reset the cursor to the original "left" value while incrementing the "top" value for each row. Note I'm also using a variable to track the column width, which I'm using to ensure that each column is the same width for each grid. This value may need to be increased if you use large numbers:
const int maxColumnWidth = 5;
static void ShowMatrix(int[,] matrix, string name)
{
var startColumn = Console.CursorLeft;
var startRow = Console.CursorTop;
Console.SetCursorPosition(startColumn, startRow);
Console.Write($"{name}:");
Console.SetCursorPosition(startColumn, ++startRow); // <-- Note this increments the row
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j].ToString().PadRight(maxColumnWidth));
}
Console.SetCursorPosition(startColumn, ++startRow); // <-- increment row again
}
}
Then, when you call the method, you can reset the cursor position back to the top and one space more to the right from the last grid that was shown (by multiplying the number of columns by the column width constant):
// code to get matrix values omitted
result = MultiplyMatrices(lhsm, rhsm);
Console.Clear();
// Capture initial cursor values
var cursorTop = Console.CursorTop;
var cursorLeft = Console.CursorLeft;
ShowMatrix(lhsm, "Matrix 1");
// Move cursor just to the right of the previous matrix, and at the same top
cursorLeft += lhsm.GetLength(1) * maxColumnWidth + 1;
Console.SetCursorPosition(cursorLeft, cursorTop);
ShowMatrix(rhsm, "Matrix 2");
// Move cursor just to the right of the previous matrix, and at the same top
cursorLeft += rhsm.GetLength(1) * maxColumnWidth + 1;
Console.SetCursorPosition(cursorLeft, cursorTop);
ShowMatrix(result, "Result");
// Move cursor back to the beginning, and just underneath the previous matrix
Console.SetCursorPosition(0, cursorTop + result.GetLength(0) + 1);
GetKeyFromUser("\nDone! Press any key to exit...");
}
Related
I can transpose a square matrix, but now I'd like to transpose a non square matrix (in my code 3*2) with user input.
Other sources recommended me to create a new matrix first, which I have done. I manage to make the matrix, but when transposing, it stops from the 4th value.
I have looked at other topics but I can't find the error. Here is my code so far, can someone tell me where I went wrong?
Thanks!
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write("Enter num: ");
matrix1[i, j] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write(matrix1[i, j] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
matrix2[j, i] = matrix1[j, i];
Console.Write(matrix2[j, i] + " ");
}
Console.WriteLine(" ");
}
This is what I get when running the program:
//output
Enter num: 1
Enter num: 2
Enter num: 3
Enter num: 4
Enter num: 5
Enter num: 6
first matrix:
1 2
3 4
5 6
transposed matrix:
1 3
2 4
//--->> Only went up to 4th value?
So, at the beginning you load a matrix with fields : "i,j" => "row, column"
On the last step, you try accessing the matrix with a "j,i" => "column, row" order.
You're inverting the i,j indexes.-
Let me help you by just changing the variable names :
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column ++)
{
Console.Write("Enter num: ");
matrix1[row, column] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{`enter code here`
Console.Write(matrix1[row, column] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{
matrix2[column, row] = matrix1[row, column];
Console.Write(matrix2[column, row] + " ");
}
Console.WriteLine(" ");
}
// EDIT : actually noticed the sample didn't traspose it properly. fixed it.
Replace
matrix2[j, i] = matrix1[j, i];
with
matrix2[j, i] = matrix1[i, j];
This way a row number of matrix1 becomes a column number for matrix2 - i.e. the matrix gets transposed.
If you combine the other two answers, you will have a complete picture:
This line is wrong and will give you an IndexOutOfRangeException:
matrix2[j, i] = matrix1[j, i];
In order to transpose you need to flip the indices:
matrix2[j, i] = matrix1[i, j];
Another problem is that when you print the matrix, you switch rows and columns.
It's easier to just extract the code for each functionality into a separate method.
Also, using the names i and j can be confusing. They look alike and they don't convey their meaning. When working with matrices, I like to use r and c (or row and column)
void PrintMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
Console.Write(m[r, c] + " ");
}
Console.WriteLine();
}
}
int[,] TransposeMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
int[,] transposed = new int[columns, rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
transposed[c, r] = m[r, c];
}
}
return transposed;
}
Then the last part of your code becomes simply:
PrintMatrix(matrix1);
Console.WriteLine();
int[,] matrix2 = TransposeMatrix(matrix1);
PrintMatrix(matrix2);
This program generates random 2d array and calculates maximum in every line. I do have right results, but IndexOutOfRangeException popping up if number of columns does not equals to the number of lines.
Random r = new Random();
int x,y;
Console.WriteLine("lines");
x = int.Parse(Console.ReadLine());
Console.WriteLine("columns");
y = int.Parse(Console.ReadLine());
if ((x < 1) || (y < 1))
{
Console.WriteLine("Error");
Console.ReadLine();
}
else
{
int[,] array1 = new int[x, y];
int[] array2 = new int[y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
array1[i, j] = r.Next(0, 51);
Console.Write(array1[i, j] + " ");
}
Console.WriteLine();
}
for (int j = 0; j < y; j++)
{
int max = array1[j, 0];
for (int i = 1; i < x; i++)
{
if (array1[j, i] > max)
{
max = (array1[j, i]);
}
else
{
}
}
array2[j] = max;
Console.WriteLine();
Console.Write(array2[j]);
}
Console.ReadLine();
}
On your second pass through the data (the one where you go by lines first rather than by columns), this:
if (array1[j, i] > max)
{
max = (array1[j, i]);
}
should look like this:
if (array1[i, j] > max)
{
max = (array1[i, j]);
}
Changing the order in which you process rows and columns doesn't change the dimensions of the array.
Edit: per #csharpfolk's comment, this line also needs fixing:
int max = array1[j, 0];
probably to:
int max = array1[0, j];
I'm trying to learn how to work with 2D-array and I can't seem to understand how to print them correctly. I want to print them in a "square" like 5x5 but all I get is one line. I've tried both WriteLine and Write and changed some of the variables in the loops but I get either an error or not the result I want to have. The code is supposed to print out a 5x5 with a random sequence of 15 numbers in each column. I get the correct numbers out of it, it's only the layout that is wrong.
static void Main(string[] args)
{
Random rnd = new Random();
int[,] bricka = new int[5, 5];
int num = 0;
int num1 = 1;
for (int i = 0; i < bricka.GetLength(1); i++)
{
num += 16;
for (int j = 0; j < bricka.GetLength(0); j++)
{
bricka[j, i] = rnd.Next(num1, num);
}
num1 += 16;
}
for (int i = 0; i < bricka.GetLength(0); i++)
{
for (int j = 0; j < bricka.GetLength(1); j++)
{
Console.Write(bricka[i, j]+ " " );
}
}
Console.ReadKey();
}
This is my print, I would like to have the the 12 under the 8 and 14 under the 12 and so on.
http://i.imgur.com/tfyRxf1.png
You need to call WriteLine() after each line, so that each line is printed on a separate line:
for (int i = 0; i < bricka.GetLength(0); i++)
{
for (int j = 0; j < bricka.GetLength(1); j++)
{
Console.Write(bricka[i, j]+ " " );
}
Console.WriteLine();
}
That would be one way of doing it, anyway.
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
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();
}
Working ideone sample
Simple solution
static void Main(string[] args)
{
// Get the number of rows
Console.WriteLine("Enter the number of rows:");
int arrayRows = Convert.ToInt32(Console.ReadLine());
// Get the number of columns
Console.WriteLine("Enter the number of columns:");
int arrayCols = Convert.ToInt32(Console.ReadLine());
// For each item in the row
for (int i = 0; i < arrayRows; i++)
{
// For each item in the column
for (int j = 0; j < arrayCols; j++)
{
// Show a star
Console.Write("*");
}
// End the line
Console.WriteLine("");
}
// Read the line to stop the app from closing
Console.ReadLine();
}
If you want to store the stars
static void Main(string[] args)
{
// Get the number of rows
Console.WriteLine("Enter the number of rows:");
int arrayRows = Convert.ToInt32(Console.ReadLine());
// Get the number of columns
Console.WriteLine("Enter the number of columns:");
int arrayCols = Convert.ToInt32(Console.ReadLine());
// Create an array
char[,] arrayTimes = new char[arrayRows, arrayCols];
char star = '*';
// For each item in the row
for (int i = 0; i < arrayRows; i++)
{
// For each item in the column
for (int j = 0; j < arrayCols; j++)
{
// Show a star
arrayTimes[i, j] = star;
}
}
// Read the line to stop the app from closing
Console.ReadLine();
}
This do what you want,
int arrayRows = 2;
int arrayCols = 2;
char[,] arrayTimes;
arrayTimes = new char[arrayRows, arrayCols];
//String star = "*";
for (int i = 0; i < arrayRows; i++)
{
for (int j = 0; j < arrayCols; j++)
{
arrayTimes[i, j] = '*';
Console.Write("{0}",arrayTimes[i, j]);
}
Console.WriteLine();
}
Console.ReadKey();
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.
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));
}
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.
private void button1_Click(object sender, EventArgs e)
{
txtResult.Text=GenerateMatrix(Int32.Parse(txtRow.Text), Int32.Parse(txtColumn.Text));
}
private string GenerateMatrix(int Row,int Column)
{
string matrix = string.Empty;
string Result = string.Empty;
int nxtline=0;
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Column; j++)
{
if (nxtline==Column)
{
matrix = matrix + Environment.NewLine;
nxtline = 0;
}
matrix = matrix+"*";
nxtline = nxtline + 1;
}
}
Result = matrix;
return Result;
}