Mostafa Ghorbani
Mostafa Ghorbani

Reputation: 445

how to add user input to 2d array in C#

I am trying to write a small program to calculate the addition of two vectors from the user and storing it in the array. I want to get two X and Y's (like this {x,y})from the user and then add them both together.

I tried to use a 2D array like so

int[,] array = new int[0, 1] {};

but I want the user to enter the values of it. I don't know enough about c# so if anyone knows how can I solve this problem would apparitions your help

Upvotes: 0

Views: 544

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

If you want to get a vector from user, you can try asking user to provide its components separated by some delimiter(s), e.g.

  private static int[] ReadVector(string title) {
    while (true) { // keep asking user until valid input is provided
      if (!string.IsNullOrEmpty(title))
        Console.WriteLine(title);

      string[] items = Console
        .ReadLine()
        .Split(new char[] { ' ', '\t', ';', ',' }, 
               StringSplitOptions.RemoveEmptyEntries);

      if (items.Length <= 0) {
        Console.WriteLine("You should provide at least one component");

        continue; 
      } 

      bool failed = false; 
      int[] result = new int[items.Length];

      for (int i = 0; i < items.Length; ++i) {
        if (int.TryParse(items[i], out int value))
          result[i] = value;
        else {
          Console.WriteLine($"Syntax error in {i + 1} term");
          failed = true;

          break;
        }  
      }

      if (!failed)
        return result; 
    }
  }

Then you can use this routine like this:

  // We don't want any 2D matrices here, just 2 vectors to sum
  int[] A = ReadVector("Please, enter vector A");
  int[] B = ReadVector("Please, enter vector B");  

  if (A.Length != B.Length) 
    Console.WriteLine("Vectors A and B have diffrent size");
  else {
    // A pinch of Linq to compute C = A + B 
    int[] C = A.Zip(B, (a, b) => a + b).ToArray();

    Console.WriteLine($"[{string.Join(", ", A)}] + ");
    Console.WriteLine($"[{string.Join(", ", B)}] = ");
    Console.WriteLine($"[{string.Join(", ", C)}]");  
  }  

Edit: Sure you can sum vectors with a help of good old for loop instead of Linq:

   int[] C = new int[A.Length];

   for (int i = 0; i < A.Length; ++i)
     C[i] = A[i] + B[i]; 

Upvotes: 2

Related Questions