- Asked 2/16
- 2070 Asar · 2 marks
- 2074 Asoj · 2 marks
Creating 1D and 2D arrays
Short answer
A 1D array is created as type name[size]; e.g., int a[5] = {10,20,30,40,50};. A 2D array is type name[rows][columns]; e.g., int b[2][3] = {{1,2,3},{4,5,6}};. Elements are accessed with zero-based indices and stored in row-major order.
How are one dimensional and two dimensional arrays created in C? Explain with examples.
An array is a collection of elements of the same data type stored in consecutive memory locations and accessed by an index that starts from 0.
One dimensional array
Syntax: data_type name[size];
It is created by giving the data type, name and size. It can be initialised at the time of declaration.
int marks[5]; /* 5 integers, garbage values */
int a[5] = {10, 20, 30, 40, 50}; /* initialised */
a[0] is 10 and a[4] is 50. The compiler reserves 5 × sizeof(int) bytes.
Two dimensional array
Syntax: data_type name[rows][columns];
It is a table (matrix) of rows and columns, stored row by row in memory. Two indices are needed to reach an element.
int b[2][3] = {{1, 2, 3}, {4, 5, 6}}; /* 2 rows, 3 columns */
b[1][2] is 6. The array holds 2 × 3 = 6 elements.
Working example
#include <stdio.h>
int main(void)
{
int a[5] = {10, 20, 30, 40, 50}; /* 1D, initialised */
int b[2][3] = {{1, 2, 3}, {4, 5, 6}}; /* 2D: 2 rows, 3 columns */
int c[3]; /* 1D, values given at run time */
for (int i = 0; i < 3; i++)
c[i] = i * i;
printf("a[2] = %d, b[1][2] = %d, c[2] = %d\n", a[2], b[1][2], c[2]);
return 0;
}
Output:
a[2] = 30, b[1][2] = 6, c[2] = 4
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Two dimensional arrays in FORTRAN · Computer Programming, chapter 11
- Array overflow/underflow; add two arrays · Computer Programming, chapter 7
- Compile time initialization of arrays · Computer Programming, chapter 7
- Linear shape functions for one-dimensional element · Finite Element Method, chapter 5
- Variational approach for one-dimensional heat conduction · Finite Element Method, chapter 5
- Derive one-dimensional heat equation · Applied Mathematics, chapter 3 · asked 5×
- Derive one-dimensional wave equation · Applied Mathematics, chapter 3 · asked 2×