Knowee
Questions
Features
Study Tools

How do you initialize a 2D array in C?

Question

How do you initialize a 2D array in C?

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is how you can initialize a 2D array in C:

  1. First, you need to declare the array with its dimensions. For example, if you want to create a 2D array with 3 rows and 4 columns, you would write:
int array[3][4];
  1. Next, you can initialize the array at the time of declaration. Here's how you can do it:
int array[3][4] = {
  {1, 2, 3, 4},
  {5, 6, 7, 8},
  {9, 10, 11, 12}
};

In this example, the numbers 1-12 are the elements of the array. The outer braces {} enclose the elements of the array, and the inner braces {} enclose the elements of each row.

  1. If you don't want to initialize the array at the time of declaration, you can do it later in your code. Here's how:
int array[3][4];

array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[0][3] = 4;
array[1][0] = 5;
array[1][1] = 6;
array[1][2] = 7;
array[1][3] = 8;
array[2][0] = 9;
array[2][1] = 10;
array[2][2] = 11;
array[2][3] = 12;

In this example, array[i][j] represents the element at the ith row and jth column. The first index represents the row number and the second index represents the column number.

This problem has been solved

Similar Questions

What is the correct way to declare a 2D array in C?

What is the correct way to declare and initialize a one-dimensional array in C?

How to initialize a two dimensional array? Give example.

How do you initialize an array in C?a.int arr[3] = (1,2,3);b.int arr(3) = {1,2,3};c.int arr[3] = {1,2,3};d.int arr(3) = (1,2,3);

How is an array initialized in C language?int (a)=[1,2,3];int a[3]={1,2,3};int a[]=new int[3]int a={1,2,3};

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.