C Arrays

Store multiple values in a single variable

📊 What are Arrays in C?

Arrays in C are collections of elements of the same data type stored in consecutive memory locations. They allow you to store multiple values under a single variable name, making data management efficient and organized.


// Simple array example
int numbers[5] = {10, 20, 30, 40, 50};
printf("First number: %d", numbers[0]);
                                    

Array Fundamentals

📋

Declaration

Define array size and type

int arr[10];  // Array of 10 integers
🔢

Initialization

Assign values to array elements

int arr[3] = {1, 2, 3};
🎯

Access

Use index to get/set values

arr[0] = 100;  // Set first element
🔄

Iteration

Loop through array elements

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

🔹 Array Declaration and Initialization

C arrays can be declared and initialized in multiple ways, each suited to different programming scenarios and initialization requirements. Basic declaration like int scores[3]; creates an uninitialized array, while int grades[4] = {88, 95, 76, 89}; initializes all elements explicitly. The compiler can automatically determine array size from initializers using int marks[] = {90, 85, 88, 92, 79};. Partial initialization like int values[10] = {1, 2, 3}; sets specified elements and zeros the rest. You can also use designated initializers in C99+ like int arr[5] = {[0] = 10, [4] = 50}; to initialize specific indices while zeroing others, providing flexibility in array setup.

// Method 1: Declare then assign
int scores[5];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;

// Method 2: Initialize during declaration
int grades[4] = {88, 95, 76, 89};

// Method 3: Let compiler determine size
int marks[] = {90, 85, 88, 92, 79};  // Size is 5

// Method 4: Partial initialization
int values[10] = {1, 2, 3};  // Rest are 0

Output:

scores[0] = 85, scores[1] = 92, scores[2] = 78

grades: 88, 95, 76, 89

marks: 90, 85, 88, 92, 79

values: 1, 2, 3, 0, 0, 0, 0, 0, 0, 0

🔹 Accessing Array Elements

Array elements are accessed using zero-based indexing with the subscript operator, providing fast direct access to any element. The syntax array[index] retrieves or modifies the element at the specified position, where valid indices range from 0 to size-1. For example, numbers[0] accesses the first element, numbers[2] the third element, and numbers[n-1] the last element in an array of size n. C doesn't perform automatic bounds checking, so accessing indices outside valid range causes undefined behavior, potentially corrupting memory or crashing the program. Always ensure your index values are within valid bounds to prevent buffer overflow vulnerabilities and program crashes.

#include <stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    
    // Access elements
    printf("First element: %d\n", numbers[0]);   // 10
    printf("Third element: %d\n", numbers[2]);   // 30
    printf("Last element: %d\n", numbers[4]);    // 50
    
    // Modify elements
    numbers[1] = 25;
    printf("Modified second element: %d\n", numbers[1]);  // 25
    
    return 0;
}

Output:

First element: 10

Third element: 30

Last element: 50

Modified second element: 25

🔹 Array Operations with Loops

Loops provide efficient mechanisms for performing operations on all array elements without repetitive code. The for loop is particularly well-suited for array processing because its counter variable naturally serves as an array index. For example, for(int i = 0; i < size; i++) iterates through each element, allowing you to perform operations like printing, summing, searching, or transforming values. Loop-based array processing enables writing scalable code that works with arrays of any size, from small datasets to large collections containing thousands of elements, without changing the algorithm structure.

#include <stdio.h>

int main() {
    int arr[5] = {2, 4, 6, 8, 10};
    int sum = 0;
    
    // Print all elements
    printf("Array elements: ");
    for(int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
        sum += arr[i];  // Calculate sum
    }
    
    printf("\nSum of elements: %d\n", sum);
    printf("Average: %.2f\n", sum / 5.0);
    
    return 0;
}

Output:

Array elements: 2 4 6 8 10

Sum of elements: 30

Average: 6.00

🔹 Common Array Operations

Essential array operations include searching for elements, finding maximum and minimum values, reversing order, and sorting elements. Linear search iterates through the array comparing each element to a target value, while binary search works efficiently on sorted arrays by repeatedly halving the search space. Finding extrema involves maintaining max/min variables while iterating through all elements. Reversing swaps elements from both ends moving toward the center, and sorting algorithms like bubble sort, quicksort, or mergesort arrange elements in ascending or descending order. Mastering these fundamental operations enables building complex data processing algorithms for real-world applications in all programming domains.

Finding Maximum Element:

int findMax(int arr[], int size) {
    int max = arr[0];
    for(int i = 1; i < size; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

Searching for an Element:

int search(int arr[], int size, int target) {
    for(int i = 0; i < size; i++) {
        if(arr[i] == target) {
            return i;  // Return index if found
        }
    }
    return -1;  // Not found
}

🧠 Test Your Knowledge

What is the index of the first element in a C array?