Multidimensional array initialization c# - c#

I have a problem initializing the following array
char[,] omar = new char[4, 4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
omar[i, j] = (char)(Console.Read());
}
}
when I try entering input like this
....
####
####
##..
It only take the first 3 lines not all the fourth , so any help please ?

You're using Console.Read() to read an individual character entered, but when you hit enter, Read() will return either:
A single linefeed character (\n, or decimal 10) if you're on a *nix-like platform;
A carriage-return character (\r, or decimal 13) if you're on Windows. The Read() call directly subsequent to this will then return a linefeed character.
A small modification to get the code you've got to work the way you expect:
char[,] omar = new char[4, 4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
omar[i, j] = (char)(Console.Read());
}
Console.Read();
if (Environment.NewLine.Length > 1)
Console.Read();
}

Related

Printing characters using Nested loops

today while I was coding I ran into a problem I couldn't figure out.
So my task is to print a chosen amount of characters, the catch is I need to also specify how much characters are in one line.
For example:
I need to print 24 characters '*'
I select the character.
Select how many: 24.
Select how many character per each line: 7.
Result should look something like this:
*******
*******
*******
***
I have to strictly use nested loops!
Code example:
static void Main(string[] args)
{
char character;
int charAmount;
int charAmountInLine;
Console.WriteLine("Select character");
character = char.Parse(Console.ReadLine());
Console.WriteLine("Select total amount of characters");
charAmount = int.Parse(Console.ReadLine());
Console.WriteLine("Select amount of characters in each line");
charAmountInLine = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = 0; i < charAmount; i++)
{
for(int j = 0; j < charAmountInLine; j++)
{
}
}
}
}
}
In this program, you need to identify:
Number of lines that print full characters in a line (row)
Print the remaining characters (remainder)
Concept:
Iterate each row (first loop).
Print character(s) in a line (nested loop in first loop).
Once print character(s) in a line is completed, print the new row and repeat Step 1 to Step 3 to print full characters in a line if any.
Print the remaining character in a line (second loop).
int row = amount / characterPerLine;
int remainder = amount % characterPerLine;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < characterPerLine; j++)
{
Console.Write(character);
}
Console.WriteLine();
}
// Print remaining character
for (int i = 0; i < remainder; i++)
{
Console.Write(character);
}
Demo # .Net Fiddle
First of all count number of rows for outer loop
int numberOfRows = (int)Math.Ceiling((double)charAmount / charAmountInLine);
for (int i = 0; i < numberOfRows; i++)
{
charAmount -= charAmountInLine;
charAmountInLine = charAmount> charAmountInLine? charAmountInLine: charAmount;
for (int j = 0; j < charAmountInLine; j++)
{
Console.Write(character);
}
Console.WriteLine("");
}
Try this one:
int row = (int)Math.Ceiling((double)charAmount/(double)charAmountInLine);
int column = 0;
int temp = 0;
for (int i = 1; i <= row; i++)
{
temp = (i * charAmountInLine);
column = temp < charAmount ? charAmountInLine : temp - charAmount;
for(int j = 0; j < column; j++)
{
Console.Write(character);
}
Console.WriteLine();
}

how to print the row of a matrix(multi-dimensional array) in a new line

I have a multi-dimensional array in C#, I have assigned the indices of the matrices by capturing input from a user, I am trying to implement a conditional structure that will let me print the rows of my matrix each on a separate line, for example if my array is A and A has a dimension of 3 by 3 then the code prints the first three elements on the first line, the next three elements on the next line and so on and so forth. I am trying to achieve this because it will be easier to understand the structure as a normal matrix and also build an entire matrix class with miscallenous operations.
Code
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
How do I modify my code so that if the array has 9 elements and its a square matrix then each row with three elements are printed on a single line.
I would use something like this for the output:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
When the inner loop is done, that means one row has been completely printed. So that's the only time the newline is needed. (n passes of the outer loop ==> n newlines printed).

How do I print # in a nested for loop [duplicate]

This question already has an answer here:
What is an "index out of range" exception, and how do I fix it? [duplicate]
(1 answer)
Closed 4 years ago.
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[6];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
Hi guys. I need to print # one and then # twice, until i get to six times. It says System.index.out.of.range. How come?
You should try to extend your array, it's limited to 6 elements but you try to access 7 elements as you go through 0 to 6.
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[7];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
If
I need to print # one and then # twice, until i get to six times.
You don't want any array - string[] doors = new string[6];, just loops:
for (int line = 1; line <= 6; ++line) {
for (int column = 1; column <= line; ++column) {
Console.Write('#');
}
Console.WriteLine();
}
If you have to work with array (i.e. array will be used somewhere else), get rid of magic numbers:
// Create and fill the array
string[] doors = new string[6];
for (int i = 0; i < doors.Length; i++)
doors[i] = "#";
// Printing out the array in the desired view
for (int i = 0; i < doors.Length; i++) {
for (int j = 0; j < i; j++) {
Console.Write(doors[j]);
}
Console.Writeline();
}
Please, notice that arrays are zero-based (array with 6 items has 0..5 indexes for them)
because it is out of range.
change it to this:
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[6];
doors[i] = "#";
for (int j = 0; j <=i.length; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
No need to use 2 loops. Just repeat that character
for (int i = 0; i <= 6; i++)
{
Console.Write(new String("#",i));
Console.WriteLine():
}

printing matrix square shape c#

I have an 8*8 matrix and here is my code:
static void Main(string[] args)
{
const int matrix_rows = 8;
const int matrix_columns = 8;
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.WriteLine(matrix[i, j]+ "\t");
}
Console.WriteLine("\n");
}
Console.ReadKey();
I want it to be printed square shape but it prints one "0" in each line. what should I do?
You write a new line each time. Do Console.Write() instead of Console.WriteLine()
It's because you're using Console.WriteLine each time in your inner loop - so every value is printed on a new line.
Also, if you replace Console.WriteLine("\n"); with Console.WriteLine(string.Empty); you won't get an extra blank line between each line.
Try this for your loop and see what you think of the output:
for (int i = 0; i < matrix_rows; i++)
{
for (int j = 0; j < matrix_columns; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine(string.Empty);
}
Because your array is empty!
Look, you create it
double[,] matrix = new double[matrix_rows, matrix_columns];
and then print it. The default value for double is 0

C#: Out of memory Exception

I have written a console application
Int64 sum = 0;
int T = Convert.ToInt32(Console.ReadLine());
Int64[] input = new Int64[T];
for (int i = 0; i < T; i++)
{
input[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < T; i++)
{
int[,] Matrix = new int[input[i], input[i]];
sum = 0;
for (int j = 0; j < input[i]; j++)
{
for (int k = 0; k < input[i]; k++)
{
Matrix[j, k] = Math.Abs(j - k);
sum += Matrix[j, k];
}
}
Console.WriteLine(sum);
}
When I gave input as
2
1
999999
It gave Out of memory exception. Can you please help.
Look at what you are allocating:
input[] is allocated as 2 elements (16 bytes) - no worries
But then you enter values: 1 and 999999 and in the first iteration of the loop attempt to allocate
Matrix[1,1] = 4 bytes - again no worries,
but the second time round you try to allocate
Matrix[999999, 999999]
which is 4 * 10e12 bytes and certainly beyond the capacity of your computer even with swap space on the disk.
I suspect that this is not what you really want to allocate (you'd never be able to fill or manipulate that many elements anyway...)
If you are merely trying to do the calculations as per your original code, there is not need to allocate or use the array, as you only ever store one value and immediately use that value and then never again.
Int64 sum = 0;
int T = Convert.ToInt32(Console.ReadLine());
Int64[] input = new Int64[T];
for (int i = 0; i < T; i++)
input[i] = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < T; i++)
{
// int[,] Matrix = new int[input[i], input[i]];
sum = 0;
for (int j = 0; j < input[i]; j++)
for (int k = 0; k < input[i]; k++)
{
//Matrix[j, k] = Math.Abs(j - k);
//sum += Matrix[j, k];
sum += Math.Abs(j - k);
}
Console.WriteLine(sum);
}
But now beware - a trillion sums is going to take forever to calculate - it won't bomb out, but you might like to take a vacation, get married and have kids before you can expect a result.
Of course instead of doing the full squared set of calculations, you can calculate the sum thus:
for (int i = 0; i < T; i++)
{
sum = 0;
for (int j = 1, term = 0; j < input[i]; j++)
{
term += j;
sum += term * 2;
}
Console.WriteLine(sum);
}
So now the calculation is O(n) instead of O(n^2)
And if you need to know what the value in Matrix[x,y] would have been, you can calculate it by the simple expression Math.Abs(x - y) thus there is no need to store that value.

Categories