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]); }
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.
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.
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.
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.
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));
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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With