An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc

Array in C

An array in C (1D array) is a collection of elements of the same data type stored in contiguous memory locations. It’s a way to group multiple values of the same type under a single name.

Declaration

The general syntax for declaring an array in C is:

data_type array_name[size];
  • data_type: The data type of the elements in the array.
  • array_name: The name of the array.
  • size: The number of elements in the array.

Initialization

You can initialize an array while declaring it:

int numbers[5] = {1, 2, 3, 4, 5};

Accessing Elements

To access an element in an array, you use its index. The index starts from 0:

int numbers[5] = {1, 2, 3, 4, 5};
printf("%dn", numbers[2]); // Output: 3

 

Multidimensional Arrays

C supports multidimensional arrays, which are arrays of arrays. For example, a 2D array can be declared as:

int matrix[3][4];

 

Passing Arrays to Functions

When passing an array to a function, the array name is actually a pointer to the first element of the array. So, the function receives a copy of the pointer, not the entire array.

 

void print_array(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("n");
}

Key Points:

  • Arrays have a fixed size, which is determined at compile time.
  • Array indices start from 0.
  • You can use array indexing to access individual elements.
  • Multidimensional arrays can be used to represent matrices or grids.
  • When passing arrays to functions, the array name is a pointer.

Example:

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }

    printf("Sum of the array elements: %dn", sum);

    return 0;
}

Related Posts

Leave a Reply