Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print the contents of an array horizontally?

Tags:

arrays

c#

.net

Why doesn't the console window print the array contents horizontally rather than vertically?

Is there a way to change that?

How can I display the content of my array horizontally instead of vertically, with a Console.WriteLine()?

For example:

int[] numbers = new int[100] for(int i; i < 100; i++) {     numbers[i] = i; }  for (int i; i < 100; i++) {     Console.WriteLine(numbers[i]); } 
like image 699
tom Avatar asked Sep 13 '10 12:09

tom


People also ask

How do I print the contents of an array?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

How do I print horizontally in C++?

Well just remove the endl from your cout and replace it with a white space, this will make the output more readable and it will print horizontally.

How do you print each element of an array to a different line?

To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.

How do you print an array in C#?

Using ForEach Method to Print the Elements of an Array We receive an array as a parameter. Then, we create a new list using ToList() method. After that, we use the built-in ForEach method, under the List class, to iterate over the array's elements. We pass to the ForEach method a lambda expression ( element => Console.


2 Answers

You are probably using Console.WriteLine for printing the array.

int[] array = new int[] { 1, 2, 3 }; foreach(var item in array) {     Console.WriteLine(item.ToString()); } 

If you don't want to have every item on a separate line use Console.Write:

int[] array = new int[] { 1, 2, 3 }; foreach(var item in array) {     Console.Write(item.ToString()); } 

or string.Join<T> (in .NET Framework 4 or later):

int[] array = new int[] { 1, 2, 3 }; Console.WriteLine(string.Join(",", array)); 
like image 170
Dirk Vollmar Avatar answered Sep 21 '22 01:09

Dirk Vollmar


I would suggest:

foreach(var item in array)   Console.Write("{0}", item); 

As written above, except it does not raise an exception if one item is null.

Console.Write(string.Join(" ", array)); 

would be perfect if the array is a string[].

like image 45
2 revs, 2 users 86% Avatar answered Sep 23 '22 01:09

2 revs, 2 users 86%