Monday, December 19, 2022

2D array initial values in java, python 3, c++ and javascript

 Here is how you can initialize a 2D array to default value 0 in each of the languages:

Java:

int[][] array = new int[3][3];

Python 3:

array = [[0] * 3] * 3

C++:

#include <array> 
std::array<std::array<int, 3>, 3> array;

JavaScript:

const array = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];


Here is how you can initialize the value of a 2D array to 5 in each of the languages:

Java:

int[][] array = new int[3][3]
for (int i = 0; i < 3; i++) { 
    for (int j = 0; j < 3; j++) { 
        array[i][j] = 5
    
}

Python 3:

array = [[5] * 3] * 3

C++:

#include <array> 
#include <algorithm> 
std::array<std::array<int, 3>, 3> array
std::fill(array.begin(), array.end(), std::array<int, 3>{5, 5, 5});

JavaScript:

const array = [[5, 5, 5], [5, 5, 5], [5, 5, 5]];

I hope this helps! Let me know if you have any questions.

No comments:

Post a Comment

Why I stopped publishing blog posts as information provider

Now the AI can generate content. Does that mean the web publishing industry reaches the end? ChatGPT said: ChatGPT Not at all. While AI can ...