Declaration and usage of arrays in the C programming language

In C language, arrays can be declared and used in the following ways:

  1. Declare an array: data type array name[array length];
    For example, declare an integer array called arr with a length of 5: int arr[5];
  2. To initialize an array: you can initialize it at the same time as declaring the array, or you can initialize it after declaring using assignment statements.
    For example, declaring an integer array arr with a length of 5 and initializing it with 1, 2, 3, 4, 5.
int arr[5] = {1, 2, 3, 4, 5};

Alternatively, declare an integer array ‘arr’ with a length of 5 and initialize it using assignment statements.

int arr[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
  1. Accessing array elements: accessing array elements using array indexes. In C language, array indexes start from 0.
    For example, accessing the first element of array ‘arr’: arr[0]
  2. The length of an array can be obtained using the sizeof operator. For example, to get the length of an array arr: int length = sizeof(arr) / sizeof(arr[0]);
  3. Traverse the array: Use a loop structure to go through each element of the array. For example, traverse the array arr and print each element.
for (int i = 0; i < length; i++) {
    printf("%d ", arr[i]);
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds