Array syntax

Declaration

type array_name[array_size];
  • type: Data type of the array elements (e.g., int, float, char).
  • array_name: Name of the array.
  • array_size: Number of elements the array can hold (must be a constant integer).
Example
int numbers[5];
  • Declares an array named numbers that can hold 5 integers.

Initialization

Arrays can be initialized at the time of declaration or afterward. Initialization can be done with a specific set of values.

Static Initialization

type array_name[array_size] = {value1, value2, ..., valueN};
  • value1, value2, …, valueN: Values to initialize the array elements.
Example
int numbers[5] = {1, 2, 3, 4, 5};
  • Declares and initializes an array numbers with the values 1, 2, 3, 4, and 5.

Partial Initialization

If fewer values than the array size are provided, the remaining elements are initialized to zero (for basic types).

int numbers[5] = {1, 2};
  • Initializes the first two elements to 1 and 2, and the remaining three elements to 0.

Implicit Size

The array size can be omitted if the initialization list is provided.

int numbers[] = {1, 2, 3, 4, 5};
  • The compiler determines the size based on the number of values provided (5 in this case).