Nano Technology

Arrays in C Programming


1. What is an Array?

An array in C is a collection of elements of the same data type stored in contiguous memory locations. Each element of an array can be accessed using a common name and an index value.

Arrays are useful when a program needs to store and process multiple values of the same type efficiently.

Arrays in C Programming

2. Declaration of Arrays

Array declaration specifies the data type, array name, and the number of elements.


data_type array_name[size];

Example:


int marks[5];
float temperature[10];

Here, memory is allocated to store the specified number of elements.

3. Initialization of Arrays

Array initialization assigns values to array elements at the time of declaration.


int numbers[5] = {10, 20, 30, 40, 50};

If fewer values are provided than the size, the remaining elements are automatically initialized to zero.

4. One-Dimensional Arrays

A one-dimensional array stores elements in a linear sequence. It is the simplest form of an array.


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

Each element is accessed using a single index value.

5. Two-Dimensional Arrays

A two-dimensional array is an array of arrays and is commonly used to represent matrices or tables.


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

It uses two indices: one for rows and another for columns.

6. Accessing Array Elements

Array elements are accessed using the array name followed by the index enclosed in square brackets.


int x = numbers[2];
int marks[5] = {80, 85, 90, 75, 95};
printf("First element: %d\n", marks[0]);   // Access element
marks[2] = 99;                          // Modify element
printf("Updated third mark: %d\n", marks[2]);

Array indexing in C starts from 0. For an array of size n, valid indices range from 0 to n-1.

7. Arrays and Loops

Loops are commonly used with arrays to read, process, and display array elements.


int i;
for (i = 0; i < 5; i++)
{
    printf("%d ", numbers[i]);
}

Using loops avoids repetitive code and improves program efficiency.

8. Examples


#include <stdio.h>

int main()
{
    int sum = 0, i;
    int a[5] = {10, 20, 30, 40, 50};

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

    printf("Sum = %d", sum);
    return 0;
}

This program calculates the sum of elements stored in a one-dimensional array.

9. Applications

  • Storing and processing student marks
  • Matrix operations
  • Searching and sorting algorithms
  • Handling large data sets
  • Implementing data structures
Note: Arrays form the foundation for advanced topics like strings, structures, pointers, and data structures.