I wrote this code for a 1D array:
int[] arr= new int[9];
arr=Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse)
It takes my whole input at once and converts it as an array besides removing spaces. Where input is 1 2 3 4 5 6 7 8 9.
This same concept was tried for 2D arrays but still can't match. Here is my code,
int[,] arr = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
arr[i, j] =Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
}
}
My input is:
1 2 3
4 5 6
7 8 9
What is the solution? How can I input the entire 2D array at once in C#?
You should call Console.ReadLine for every line and then put in the values:
int[,] arr = new int[3, 3];
for (int i = 0; i < 3; i++)
{
int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
for (int j = 0; j < 3; j++)
{
arr[i, j] = temp[j];
}
}
Related
how can I input an integer array sideways not downward? suppose it has array [2,2] then in c # :
input :
1
2
3
4
I want to store like this:
1 2
3 4
what should i do? I am confused, as for the code I use:
int length = Convert.ToInt16(Console.ReadLine());
int[,] box = new int[length, 2];
for(int i = 0; i<length; i++){
for(int j = 0; j<2; j++){
photo[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
static void Main(String[] args){
int length = Convert.ToInt32(Console.ReadLine());
int[,] box = new int[length, 2];
for (int i = 0; i < length; i++){
box[i, 0] = Int32.Parse(Console.ReadLine());
box[i, 1] = Int32.Parse(Console.ReadLine());
}
}
As you have mentioned that you have two columns it might give you a better understanding.For each row since we have two columns due to that I we are fetching values two times.
sorry for noob question :). I've got 2d array 3x3 filled with random numbers (-5,5)
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
dPole[i, j] = nc.Next(-10, 10);
I want all the numbers that are positive and then save them into 1d array:
foreach (int j in dPole)
{
if (j > 0)
{
Console.WriteLine(j);
for (int i = 0; i < sizeOf1dArray; i++)
jPole[i] = j;
}
}
Output of Console.WriteLine(j)- to check if the condition is right:
6
2
5
6
9
8
Output of 1d Array:
8
8
8
8
8
8
Only the last number is saved into array. Why? Thanks.
An alternative route would be to use Cast<int> to flatten the array and use Where to filter.
int[,] dPole = new int[,] { { 3, -5, 0 }, { -3, 3, 2 }, { -2, 1, 1 } };
int[] jPole = dPole.Cast<int>().Where(i => i > 0).ToArray();
// jPole is now { 3, 3, 2, 1, 1 };
for (int i = 0; i < sizeOf1dArray; i++)
jPole[i] = j;
because at this loop action last j value is 8 and this loop fills all jPole array with j value every time, that means it fills all with 6 first, than puts 2 at entire array, then 5...... and for last it fills it with 8.
try something like that
int i = 0;
foreach (int j in dPole)
{
if (j > 0)
{
Console.WriteLine(j);
jPole[i] = j;
i++;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
using System;
class TwoD
{
static void Main()
{
int[][,] a = new int[3][,];
a[0] = new int[2, 2];
// a[1] = new int[3, 3];
int i,j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[0][i,j] = i;//confused
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine(a[0][i, j] + " ");
Console.WriteLine();
}
}
This is the program and the output is
0
0
1
1
But i am little bit confused about initialisation of jagges array where i have commented. Please tell me the initialisation of jagged two dimentional array and correct me if i am wrong.
Not sure about where you are confused but I guess only confusion is about mixture of jagged array and multidimensional array. i.e. a[][] is jagged array, the second dimension can have any (or no) length. You have to initialize each dimension in a separate look While multidimensional array have same length for each dimension and that's why you can pre-initialize the multidimensional array. Like a[2,5].
Below example will explain more about initialization of each kind of array and how you can write more dynamic code of your example.
//jagged array sample of initialization
int[][] jagged = new int[3][];
for (int i = 0; i < jagged.Length; i++)
jagged[i] = new int[i + 4]; //each element of jagged array can have different length
//multidimensional array sample of initialization
int[,] multiD = new int[3, 4]; //that's it.
//multiD.GetLength(0) is 3 and multiD.GetLength(1) is 4
//Your example.
int[][,] a = new int[3][,];
a[0] = new int[2, 2];
a[1] = new int[3, 4];
int interationOrder = 0;
for (int jag = 0; jag < a.Length; jag++)
{
//considering rank of multidimentional array is always 2 (Rank of [,] = 2, Rank of [,,] = 3)
if (a[jag] == null)
continue;
for (int i = 0; i < a[jag].GetLength(0); i++)
{
for (int j = 0; j < a[jag].GetLength(1); j++)
{
a[jag][i, j] = interationOrder++;//no confusion :) this is corret.
}
}
}
I've been bugged with this idea for a while.
Accepting an array with spaces is not straight forward in c#. How do we accept a 2d array, whose size is given by the user? I tried this, but something isn't right. Help is much appreciated. Thank You.
Input:
4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Where the first line specifies the value of 'n' in 'n x n'
Well, the code i tried was this. This might look stupid for a few of you :
string input;
string[] inputArray;
int[] inputInt;
int MxM = Convert.ToInt32(Console.ReadLine()); //MxM = First Line=n
int[,] array = new int[MxM, MxM];
for (int i = 0; i < MxM; i++)
{
for (int j = 0; j < MxM; j++)
{
input = Console.ReadLine();
inputArray = input.Split(' ');
inputInt = new int[MxM];
for (int k = 0; k < MxM; k++)
{
inputInt[k] = int.Parse(inputArray[k]);
array[i, j] = inputInt[k];
}
}
}
Hopefully, the answer for this will also be the answer to output a matrix. Thank You
Either:
for (int i = 0; i < MxM; i++)
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(Console.ReadLine());
or:
for (int i = 0; i < MxM; i++)
{
inputArray = Console.ReadLine().Split(' ');
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(inputArray[j]);
}
which, of course, could fail if you don't enter in the right format.
If I am understanding what you want correctly:
You would like to take an input N, in your example 4, with that - create a 4 x 4 array. Then for each index in the first dimension, ask the user for input equating to N number of integers separated by spaces. Read that input and place it into the array at the proper 2d-index. So with 4 as the first input, the user will be prompted something like:
Please input 4 integers(separated by spaces):
The user would type in, for example:
Please input 4 integers(separated by spaces): 1 2 3 4
And hit enter. Again the user is prompted:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces):
And so on until:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces): 2 3 4 5
Please input 4 integers(separated by spaces): 3 4 5 6
Please input 4 integers(separated by spaces): 4 5 6 7
You could probably use something like the following in this case:
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Please enter the size of the matrix:");
if (!int.TryParse(Console.ReadLine(), out size))
{
Console.WriteLine("The value provided for the size was not a proper integer value.");
Console.WriteLine("Press ESC to quit...");
while (Console.ReadKey().Key != ConsoleKey.Escape) { }
return;
}
int[,] matrix = new int[size, size];
for (int i = 0; i < size; ++i)
{
bool complete = false;
while (!complete)
{
Console.WriteLine(string.Format("[{0}] - Please input {1} integers(separated by spaces):", i, size));
string[] input = Console.ReadLine().Split(' ');
if (input.Count() != size)
{
Console.WriteLine("The input was invalid, try again...");
continue;
}
for (int j = 0; j < size; ++j)
{
if (!int.TryParse(input[j], out matrix[i, j]))
{
complete = false;
Console.WriteLine("The input was invalid, try again...");
break;
}
complete = true;
}
}
}
Console.WriteLine("Output: \n");
WriteMatrix(matrix, size);
Console.ReadKey();
}
private static void WriteMatrix(int[,] matrix, int size)
{
string output = string.Empty;
for(int i = 0; i < size; ++i)
{
string line = string.Empty;
for (int j = 0; j < size; ++j)
line += string.Format("{0} ", matrix[i, j]);
output += string.Format("{0}\n", line.Trim());
}
Console.WriteLine(output);
}
}
The code above should be mostly safe against the user typing invalid values, but you could probably spend some time to clean it up or enhance it some more. The basic idea is there.
You can try to use code like this:
Console.ReadLine().Split().Select(str => Convert.ToInt32(str)).ToArray()
to get an int array out of the line.
I think you understood the idea.
public static int[,] MatrixConstructor()
{
int N = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++)
{
String[] line = Console.ReadLine().Split(' ');
for (int j = 0; j < N; j++)
{
matrix[i,j] = Convert.ToInt32(line[j]);
}
}
return matrix;
}
This conforms to your input.
I've got the following arrays:
int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };
What I'd like to know how to do is:
Create a new array with the sum of myArray1 and myArray2
Create a new array with the subtraction of myArray1 and myArray2
Create a new array with the multiplication of myArray1 and myArray2
Result of sum would be:
int[,] myArray3 = new int[2, 3] { { 7, 6, 0 }, { -4, 4, 0 } };
Result of subtraction would be:
int[,] myArray3 = new int[2, 3] { { 5, 2, 6 }, { 12, 8, 16 } };
Result of multiplication would be:
int[,] myArray3 = new int[2, 3] { { 6, 8, 9 }, { 32, 12, 64 } };
Can this be done similar to printing out the arrays, with for loops? I tried looking for examples but found none that I could use for my specific problem.
int[,] a3 = new int[2,3];
for(int i = 0; i < myArray1.GetLength(0); i++)
{
for(int j = 0; j < myArray1.GetLength(1); j++)
{
a3[i,j] = myArray1[i,j] + myArray2[i,j];
a3[i,j] = myArray1[i,j] - myArray2[i,j];
a3[i,j] = myArray1[i,j] * myArray2[i,j];
}
}
need to store a3 before doing a new calculation obviously
For Sum:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = myArray1[i, j] + myArray2[i, j];
}
}
For Subtraction:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = myArray2[i, j] - myArray1[i, j];
}
}
For Multiplication:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = A[i, j] * B[i, j];
}
}
Yes this would be done exactly like printing out the arrays with for loops
c# has foreach loops which would be even easier to use
Note: I get the idea this is for homework so I'm not going to give a 100% conclusive end all be all answer.
int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };
foreach (int[] a1 in myArray1)
{
foreach(int i in a1)
{
//operation here
//you get the idea
}
}
If you want to do array manipulation faster use the C# Parallel.For loop from System.Threading.Tasks:
For simple arithmetic parallelizing the outer loop is much faster than not on a modern PC processor. For more complex operations, or for small array sizes, the parallel version can be slower for various reasons.
Thus, use a stopwatch to time your matrix operations, and use the fastest solution. Parallelization makes doing array / image processing in C# much faster if implemented right.
Beware of overflowing your datatypes after arithmetic operations and also sharing variables between multiple threads (see System.Threading.Interlocked for help with that)...
Subtraction below. Similar for addition and multiplication:
Parallel.For(0, array.GetLength(1), y=>
{
for (int x = 0; x < array.GetLength(0); x++)
{
difference[x,y] = minuend[x,y] - subtrahend[x,y];
}
}
});
If you want to use a for loop, you can iterate through the rows/columns of the multi-d array as follows:
for (int i = 0; i < myArray1.GetLength(0); i++)
{
for (int j = 0; j < myArray1.GetLength(1); j++)
{
// Here, you can access the array data by index, using i and j.
// Ex, myArray1[i, j] will give you the value of 1 in the first iteration.
}
}
Note: When you pass a value into the Array's GetLength method, it represents the dimension of the array. See http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx