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();
Related
I have to write a program that creates a two dimensional array and fills it like a snake. Here is the task itself:
Blockquote write a program that creates a two-dimensional numeric array and this array is filled with a "snake": first the first row (from left to right), then the last column (from top to bottom), the last row (from right to left), the first column (from bottom to top), the second row ( left to right), etc.
I tried to write something, but bugs constantly appear. Please help to shorten this code and make it correct.
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int len = rand.Next(5, 20);
int wid = rand.Next(5, 20);
int[,] arr = new int[len, wid];
int num = 10;
int line = 0;
int line2 = len;
int col = wid - 1;
int col2 = 0;
for (int i = 0; i <= (len > wid ? len : wid); i++)
{
for (int k = 0; k < wid; k++, num++)
{
arr[line, k] = num;
}
line++;
for (int k = 0; k < len; k++, num++)
{
arr[k, col] = num;
}
col++;
for (int k = (wid - 1); k >= 0; k--, num++)
{
arr[line2, k] = num;
}
line2++;
for (int k = 0; k < (len - 1); k++, num++)
{
arr[k, col2] = num;
}
col2++;
}
for (int i = 0; i <= len; i++)
for (int q = 0; q <= wid; q++)
{
Console.WriteLine(arr[i, q] + " ");
}
}
}
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...");
}
I have this function to initiate a two dimensional array:
static Array Matrix(int Rows, int Columns)
{
int[,] LotteryArray = new int[Rows,Columns];
for (int i = 0; i < LotteryArray.GetLength(0); i++)
{
for (int j = 0; j < LotteryArray.GetLength(1); j++)
{
LotteryArray[i, j] = RandomNum(1, 46);
Console.Write("{0,3},", LotteryArray[i, j]);
}
Console.WriteLine();
}
return LotteryArray;
}
Then I have this which is supposed to give me a one dimensional array and see how many numbers in the winning array are in the matrix:
int RowNum = 1;
int Prediction = 0;
Console.WriteLine("Your winning numbers are!");
Console.WriteLine("------------------------");
int[] Winner = new int[6];
for (int i = 0; i < Winner.Length; i++) //this loop is to initiate and print the winning numbers
{
Winner[i] = RandomNum(1, 46); //the numbers are supposed to be between 1 and 45, so i tell it to do it until 46 because the upper limit is exclusive
Console.Write("{0,3},", Winner[i]);
}
Console.WriteLine();
Console.WriteLine("------------------------"); //these two lines are for aesthetics
Matrix(Rows, Columns);
foreach (int i in Winner)
{
for (int j = 0; j<LotteryArray; j++)
{
if (Winner[i] == j)
{
Prediction++;
if (j % 6 == 0) { RowNum++; }
}
Console.WriteLine("you got {0} correct prediction in row number {1}",Prediction,RowNum);
RowNum = 1;
}
}
It's telling me LotteryArray doesn't exist in the current context.
LotteryArray is a variable within another method. You cannot access it in the scope you are showing.
You can do get the return from your method into a variable and then use it.
var LotteryArray = Matrix(Rows, Columns);
foreach (int i in Winner)
{
for (int j = 0; j<LotteryArray; j++)
{
if (Winner[i] == j)
{
Prediction++;
if (j % 6 == 0) { RowNum++; }
}
Console.WriteLine("you got {0} correct prediction in row number {1}",Prediction,RowNum);
RowNum = 1;
}
}
LotteryArray is a variable declared in Matrix method, and is not visible outside.
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.
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;
}