czolbe
czolbe

Reputation: 611

C# For Loop and Array (practice exercise)

I'm trying to pick up C# and have been doing some practice programs. In this one, I try to transfer the integers in practiceArray to practiceArray2 but am unsuccessful, instead obtaining this as the output:

System.Int32[]
System.Int32[]

The code of my program is as follows:

static void Main(string[] args)
    {
        int[] practiceArray = new int[10] {2,4,6,8,10,12,14,16,18,20 };
        int[] practiceArray2 = new int[practiceArray.Length];

        for (int index = 0; index < practiceArray.Length; index++) 
        {
            practiceArray2[index] = practiceArray[index];
        }

        Console.WriteLine(practiceArray);
        Console.WriteLine(practiceArray2);


    }

Upvotes: 0

Views: 864

Answers (2)

Umut D.
Umut D.

Reputation: 1846

int[] practiceArray = new int[10] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int[] practiceArray2 = new int[practiceArray.Length];

  for (int index = 0; index < practiceArray.Length; index++)
  {
    practiceArray2[index] = practiceArray[index];
  }

  foreach (int pArray in practiceArray)
    Console.Write(pArray + " ");      

  foreach (int pArray2 in practiceArray2)
    Console.Write(pArray2 + " ");

  Console.Read();

Upvotes: 0

Alex Paven
Alex Paven

Reputation: 5549

Console.WriteLine doesn't have any complicated logic for outputting complex objects, it just calls ToString() if it's not a string. You need to concatenate the values in the arrays manually, using string.Join etc.

For instance: Console.WriteLine(string.Join(", ", practiceArray));

Upvotes: 1

Related Questions