Virtual assistance

C Programming Tutorial

Welcome to AIVista --India's tutorial pages on C Programming

C Programming

Arrays in C

Arrays are fundamental data structures in C that store multiple elements of the same data type in contiguous memory locations.

"An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together."

What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays provide a way to store multiple values of the same type under a single variable name.

Types of Arrays in C

Type Description Dimensions
One Dimensional Array Linear array with single row 1D
Two Dimensional Array Array with rows and columns (matrix) 2D
Multi Dimensional Array Array with multiple dimensions 3D, 4D, etc.

One Dimensional Arrays

Declaration and Initialization

// Declaration
data_type array_name[size];

// Examples
int numbers[5];           // Declaration
int marks[5] = {85, 92, 78, 96, 88};  // Initialization
float prices[] = {10.5, 20.3, 15.7};  // Size determined by initializer
char name[20] = "AIVista India";       // String array

Accessing Array Elements

#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};

    // Accessing elements using index (0-based)
    printf("First element: %d\n", arr[0]);    // 10
    printf("Third element: %d\n", arr[2]);    // 30
    printf("Last element: %d\n", arr[4]);     // 50

    return 0;
}

Array Operations

#include <stdio.h>

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

    // Calculate sum
    for(int i = 0; i < 5; i++) {
        sum += arr[i];
    }
    printf("Sum: %d\n", sum);

    // Find maximum
    for(int i = 1; i < 5; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }
    printf("Maximum: %d\n", max);

    return 0;
}

Two Dimensional Arrays

Declaration and Initialization

// Declaration
data_type array_name[rows][columns];

// Examples
int matrix[3][3];         // 3x3 matrix
int table[2][4] = {
    {1, 2, 3, 4},         // Row 0
    {5, 6, 7, 8}          // Row 1
};

// Partial initialization
int arr[3][3] = {
    {1, 2},                // Row 0: 1, 2, 0
    {4, 5, 6},             // Row 1: 4, 5, 6
    {7}                    // Row 2: 7, 0, 0
};

Accessing 2D Array Elements

#include <stdio.h>

int main() {
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // Accessing elements
    printf("Element at [0][0]: %d\n", matrix[0][0]);  // 1
    printf("Element at [1][2]: %d\n", matrix[1][2]);  // 6
    printf("Element at [2][1]: %d\n", matrix[2][1]);  // 8

    return 0;
}

Matrix Operations

#include <stdio.h>

#define ROWS 3
#define COLS 3

int main() {
    int matrix[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    printf("Matrix:\n");
    for(int i = 0; i < ROWS; i++) {
        for(int j = 0; j < COLS; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    // Calculate sum of diagonal elements
    int diagonal_sum = 0;
    for(int i = 0; i < ROWS; i++) {
        diagonal_sum += matrix[i][i];
    }
    printf("Diagonal sum: %d\n", diagonal_sum);

    return 0;
}

Array Memory Representation

Arrays in C are stored in contiguous memory locations. The address of each element can be calculated using:

Address of arr[i] = Base Address + (i × Size of each element)

Array Size and Memory

#include <stdio.h>

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

    printf("Size of array: %lu bytes\n", sizeof(arr));
    printf("Size of int: %lu bytes\n", sizeof(int));
    printf("Number of elements: %lu\n", sizeof(arr)/sizeof(int));

    // Memory addresses
    printf("Base address: %p\n", arr);
    printf("Address of arr[0]: %p\n", &arr[0]);
    printf("Address of arr[1]: %p\n", &arr[1]);

    return 0;
}

Passing Arrays to Functions

Passing 1D Array

#include <stdio.h>

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

int sumArray(int arr[], int size) {
    int sum = 0;
    for(int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

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

    printArray(numbers, 5);
    printf("Sum: %d\n", sumArray(numbers, 5));

    return 0;
}

Passing 2D Array

#include <stdio.h>

#define ROWS 3
#define COLS 3

void printMatrix(int matrix[ROWS][COLS]) {
    for(int i = 0; i < ROWS; i++) {
        for(int j = 0; j < COLS; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    printMatrix(matrix);
    return 0;
}

Common Array Problems

1. Linear Search

#include <stdio.h>

int linearSearch(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;  // Return -1 if not found
}

int main() {
    int arr[5] = {10, 25, 8, 45, 12};
    int target = 45;

    int result = linearSearch(arr, 5, target);
    if(result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found\n");
    }

    return 0;
}

2. Array Reversal

#include <stdio.h>

void reverseArray(int arr[], int size) {
    int start = 0;
    int end = size - 1;

    while(start < end) {
        // Swap elements
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        start++;
        end--;
    }
}

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

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

    reverseArray(arr, 5);

    printf("\nReversed array: ");
    for(int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Advantages of Arrays

  • Random access to elements using index
  • Easy to implement and use
  • Memory efficient for storing multiple elements of same type
  • Cache-friendly due to contiguous memory allocation

Limitations of Arrays

  • Fixed size (cannot be resized after declaration)
  • Insertion and deletion operations are expensive
  • Waste of memory if not fully utilized
  • No built-in bounds checking

Best Practices

  • Always check array bounds to avoid overflow
  • Use meaningful variable names for arrays
  • Initialize arrays properly to avoid garbage values
  • Consider dynamic memory allocation for variable-sized arrays
  • Use const qualifier for arrays that shouldn't be modified

Conclusion

Arrays are essential building blocks in C programming. They provide efficient storage and access to multiple elements of the same type. Understanding arrays is crucial for working with more complex data structures and algorithms. Practice with different array operations to master this fundamental concept! 🚀