Home > Software engineering >  how to fill 2d array in c without user input
how to fill 2d array in c without user input

Time:06-05

how to fill 2d array in c without user input or how to predefined an 2d array in c I was tried like this way int a[100][100]={ {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, {1,2,3,4,5,6,7,8,9,10} };

but it's can't work properly

CodePudding user response:

The example you gave works correctly. After assignment, "a" is a 2d array of numbers that you have written. The first positions in the first 2 rows of this 2d array assigned to the numbers you have written. And all other elements of this array were set to zero.

According to the C11 standard there are several ways to initialize multidimensional arrays:

The declaration

int y[4][3] = {
{ 1, 3, 5 },
{ 2, 4, 6 },
{ 3, 5, 7 },
};

is a definition with a fully bracketed initialization: 1, 3, and 5 initialize the first row of y (the array object y[0]), namely y[0][0], y[0][1], and y[0][2]. Likewise the next two lines initialize y[1] and y[2]. The initializer ends early, so y[3] is initialized with zeros. Precisely the same effect could have been achieved by

int y[4][3] = {
1, 3, 5, 2, 4, 6, 3, 5, 7
};

The initializer for y[0] does not begin with a left brace, so three items from the list are used. Likewise the next three are taken successively for y[1] and y[2].

CodePudding user response:

Syntax of a 2D array declaration is data_type array_name[rows][columns].

int arr[3][5];

In the above example, 3 is the number of rows. 5 is the number of columns. There are two ways that we can initialize a 2D array. First way is,

int arr[3][5] = {
 {1, 2, 3, 4, 5},
 {6, 7, 8, 9, 10},
 {11, 12, 13, 14, 15}
 };

In this method we write 5 elements (since we have 5 columns) which are in the same row, inside {}. For example, {1, 2, 3, 4, 5} is the first entire row. Likewise, we write all 3 rows and separate each row using a comma. All those comma separated groups are included in a single{}.

The second way is,

int arr[3][5] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

The recommended way is first method. The number of elements that can be present in a 2D array will always equal to Number of rows * Number of columns.

In your code, you have not given all the column values. So, only the first 15 values will be printed according to your code. Other indexes will be replaced by zero. Since it is hard to give all values as there are 100 rows and 100 columns, we can initialize all values to zero by using the following method.

int arr[3][5] = {0};
  •  Tags:  
  • c
  • Related