BCA TU, C Programming – Unit 7: Array

Arrays are used to store multiple values of the same type under a single name. They help in organizing data and make operations like sorting and searching efficient.


1. Declaration and Initialization

Declaration: Specifies the type and size of the array.

int marks[5];  // Array of 5 integers

Initialization: Assigns values at the time of declaration.

int marks[5] = {40, 50, 60, 70, 80};

  • Default initialization: Uninitialized elements contain garbage values (for local arrays).
  • Partially initialized: Remaining elements are set to 0.

2. One-Dimensional Array

  • Stores elements in a single row.
  • Accessed using a single index: array[index].

printf(“%d”, marks[2]);  // Prints 60

  • Can be traversed using loops.

for(int i = 0; i < 5; i++) {

    printf(“%d “, marks[i]);

}


3. Multi-Dimensional Array

  • Example: Two-dimensional array (matrix).

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

  • Access element: matrix[row][column].

printf(“%d”, matrix[1][2]);  // Prints 6

  • Useful for tables, matrices, and grids.

4. Sorting

(a) Bubble Sort
Repeatedly compares adjacent elements and swaps if out of order.

for(int i=0; i<n-1; i++) {

    for(int j=0; j<n-i-1; j++) {

        if(arr[j] > arr[j+1]) {

            int temp = arr[j];

            arr[j] = arr[j+1];

            arr[j+1] = temp;

        }

    }

}

(b) Selection Sort
Selects the minimum element and places it in correct position.

for(int i=0; i<n-1; i++) {

    int min_idx = i;

    for(int j=i+1; j<n; j++) {

        if(arr[j] < arr[min_idx]) min_idx = j;

    }

    int temp = arr[i];

    arr[i] = arr[min_idx];

    arr[min_idx] = temp;

}


5. Searching

Sequential (Linear) Search

  • Checks each element one by one until the target is found.

for(int i=0; i<n; i++) {

    if(arr[i] == key) {

        printf(“Found at %d”, i);

        break;

    }

}

  • Simple but inefficient for large arrays.

6. String Handling

  • Strings are arrays of characters ending with a null character ‘\0’.

char name[10] = “Alice”;

  • Common operations:
    • strlen(name) → Length of string
    • strcpy(dest, src) → Copy string
    • strcmp(str1, str2) → Compare strings
    • strcat(dest, src) → Concatenate strings

Key Takeaways

  • Arrays store multiple elements of the same type under one name.

1D Array: Single row of elements.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.