Print an Array as Code

print an array as code

You're looking for var_export.

What's the simplest way to print a Java array?

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

Examples:

  • Simple Array:

    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));

    Output:

    [John, Mary, Bob]
  • Nested Array:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    // Gives undesired output:
    System.out.println(Arrays.toString(deepArray));
    // Gives the desired output:
    System.out.println(Arrays.deepToString(deepArray));

    Output:

    [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    [[John, Mary], [Alice, Bob]]
  • double Array:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));

    Output:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
  • int Array:

    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));

    Output:

    [7, 9, 5, 1, 3 ]

How can I print an int array in C in one line (meaning, without for loops)?

No,In C you cannot print array with single line of code, there is no inbuilt function available in C to print the array in single line.

Python also doesn't print array in single line, it does use loops but those functions are not visible to us.

How ever there are ways by which we can print C array without for-loop, You can refer this Question answered in stack overflow for that.

Is printing array possible without any loop in the C Language?

How to print an array of strings

The reason you can print strings in main() but not in print_array is the result of how an array is converted to a pointer on access. What this means is that when you access an array (subject to 4 exceptions below) the array is converted to a pointer to the first element in the array. After the conversion takes place, as it does when you pass an array as a parameter to a function, you have only a pointer, not an array.

The C11 Standard (as well as the C17 Standard) reads as follows:

Array pointer conversion

(p3) Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary '&' operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.
C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)

If you note above, when used with the sizeof operator, and array is not converted to a pointer, so in main(), sizeof(strings) / sizeof(strings[0]) provides the number of elements in the array of string. However, after you pass strings to print_array, the conversion to pointer has already occurred, so that in print_array your attempted use of sizeof results in:

size_t array_length = sizeof(a_pointer) / sizeof(a_char);

(which is 8 on x86_64, or 4 on x86)

You have two choices (1) pass the number of elements in your array as a second parameter to print_array, or (2) make the last pointers in strings NULL (to be used as a sentinel value). Then in print_array you can just iterate over strings[i] until it is NULL.

A couple of quick examples:

Passing the Number of Elements

#include <stdio.h>

void print_array (char **strings, size_t nptrs)
{
for (size_t i = 0; i < nptrs; i++)
printf("%s, ", strings[i]);
putchar ('\n');
}

int main(void) {

char *strings[] = { "Hello",
"Zerotom",
"new" };

print_array (strings, sizeof strings/sizeof *strings);

return 0;
}

Example Use/Output

$ ./bin/prnarray
Hello, Zerotom, new,

Adding a Sentinel NULL to strings

#include <stdio.h>

void print_array (char **strings)
{
for (size_t i = 0; strings[i]; i++)
printf("%s, ", strings[i]);
putchar ('\n');
}

int main(void) {

char *strings[] = { "Hello",
"Zerotom",
"new",
NULL }; /* sentinel NULL */

print_array (strings);

return 0;
}

(same output)

There are at least a handful of ways to loop using either for or while loops and either using a pointer to strings and pointer arithmetic, or using array indexing (the difference are simple semantics as you are doing the same thing). Look things over and let me know if you have further questions.

How can I echo or print an array in PHP?

This will do

foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}

How do I print name of array in Python?

you can use a class to store the array and the name, then you can access with
.name o .array

class Foo():
def __init__(self, array, name):
self.array = array
self.name = name

my_array = [1,2,3,4]
XYZ=Foo(my_array, "name")

print(XYZ.array)
print(XYZ.name)

printing all contents of array in C#

You may try this:

foreach(var item in yourArray)
{
Console.WriteLine(item.ToString());
}

Also you may want to try something like this:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));

EDIT: to get output in one line [based on your comment]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
//output style: [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]

EDIT(2019): As it is mentioned in other answers it is better to use Array.ForEach<T> method and there is no need to do the ToList step.

Array.ForEach(yourArray, Console.WriteLine);


Related Topics



Leave a reply



Submit