ITM102 Structured Programming in C

Structured Programming in CUnit 412 min read

Arrays, Strings & Their Operations in C

Unit 4 of Structured Programming in C covers arrays (1D/2D), strings, their initialization, traversal, searching, sorting, and applications in real-world problems like inventory management and text processing.

TAKEAWAYS:

  • Arrays store homogeneous data in contiguous memory, enabling efficient access via indices.
  • Strings in C are null-terminated character arrays (char[]) with unique operations like strlen() and strcpy().
  • Sorting algorithms (e.g., Bubble Sort) and searching (Linear/Binary) are fundamental for optimizing data retrieval.
  • 2D arrays represent matrices, useful in graphics, statistics, and game development.
  • Pointer arithmetic and arrays are deeply connected, enabling flexible memory manipulation.
  • Real-world applications include order queues (Pathao), inventory tracking (Daraz), and text processing (eSewa).

1. Arrays: The Backbone of Structured Data

Arrays are contiguous memory locations storing elements of the same data type. They enable efficient access via indices (starting at 0 in C).

1.1 One-Dimensional Arrays

  • Declaration: dataType arrayName[size];
    int marks[5]; // Array of 5 integers
    
  • Initialization:
    int numbers[] = {10, 20, 30, 40, 50}; // Size inferred
    
  • Accessing Elements: arrayName[index]
    printf("%d", numbers[2]); // Output: 30
    
100201302403504
Example of a 1D array with 5 elements (indices 0-4)

1.2 Two-Dimensional Arrays (Matrices)

  • Declaration: dataType arrayName[rows][columns];
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
  • Accessing Elements: arrayName[row][column]
    printf("%d", matrix[1][2]); // Output: 6
    
1,2,304,5,617,8,92
3×3 matrix example (rows 0-2, columns 0-2)

1.3 Key Operations

Operation Example Code Time Complexity
Traversal for (int i=0; i<size; i++) O(n)
Searching Linear Search: for (i=0; arr[i]!=key; i++) O(n)
Sorting Bubble Sort (see below) O(n²)

1.4 Worked Example: Linear Search in an Array

Problem: Search for 30 in numbers = {10, 20, 30, 40, 50}. Code:

#include <stdio.h>
int linearSearch(int arr[], int size, int key) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == key) return i;
    }
    return -1; // Not found
}
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int key = 30;
    int result = linearSearch(arr, 5, key);
    printf("Element found at index: %d", result);
    return 0;
}

Trace Table:

Step i arr[i] Condition (arr[i] == key) Action
1 0 10 False Continue
2 1 20 False Continue
3 2 30 True Return 2

Real-World Tie-In: Pathao uses arrays (or linked lists) to manage order queues. When a rider accepts an order, the system removes that order from the queue (like dequeue() in a queue). If the queue is implemented as an array, the system shifts all remaining elements left to fill the gap, ensuring O(n) time complexity for deletions.


2. Strings: Special Character Arrays

Strings in C are null-terminated character arrays (\0 marks the end).

  • Declaration:
    char name[] = "Alice"; // Equivalent to {'A', 'l', 'i', 'c', 'e', '\0'}
    
  • Key Functions:
    Function Description Example
    strlen() Returns string length (excluding \0) strlen("Hi") → 2
    strcpy() Copies one string to another strcpy(dest, "Hello")
    strcat() Concatenates two strings strcat("Hi", "!") → "Hi!"
    strcmp() Compares two strings strcmp("a", "b") → -1

2.1 Worked Example: String Concatenation

Problem: Concatenate "Hello" and "World". Code:

#include <stdio.h>
#include <string.h>
int main() {
    char str1[20] = "Hello";
    char str2[] = "World";
    strcat(str1, str2); // str1 becomes "HelloWorld"
    printf("%s", str1);
    return 0;
}

Trace:

  1. str1 initially: {'H', 'e', 'l', 'l', 'o', '\0'}
  2. After strcat(): {'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '\0'}
Hello0 1World2
String concatenation: "Hello" + " " + "World" → "Hello World"

Real-World Tie-In: eSewa processes user input strings (e.g., phone numbers, transaction IDs) using string functions like strcmp() to validate formats. For example:

if (strcmp(userInput, "1234567890") == 0) {
    // Proceed with transaction
}

3. Sorting Algorithms: Organizing Data

Sorting rearranges elements in a specific order (ascending/descending). Common algorithms:

Algorithm Time Complexity (Avg) Space Complexity Best Use Case
Bubble Sort O(n²) O(1) Small datasets
Selection Sort O(n²) O(1) Minimizing swaps
Insertion Sort O(n²) O(1) Nearly sorted data

3.1 Bubble Sort: Repeated Swaps

Problem: Sort arr = {64, 34, 25, 12, 22} in ascending order. Code:

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        for (int j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                // Swap
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

Trace Table (First Pass):

Step i j arr[j] arr[j+1] Swap? Array State
1 0 0 64 34 Yes 34, 64, 25, 12, 22
2 0 1 64 25 Yes 34, 25, 64, 12, 22
3 0 2 64 12 Yes 34, 25, 12, 64, 22
4 0 3 64 22 Yes 34, 25, 12, 22, 64

Visualization (After Each Pass):

640341252123224
Initial array (unsorted)

Real-World Tie-In: NEPSE (Nepal Stock Exchange) sorts stock prices in ascending/descending order for traders. For example, if a trader wants to see the top 10 highest-priced stocks, the system uses a sorting algorithm (often QuickSort for efficiency) to arrange the data before displaying it.


4. Two-Dimensional Arrays: Matrices

Used for tables, grids, and mathematical operations. Example: Representing a 5x5 game board in Tic-Tac-Toe.

char board[5][5] = {
    {' ', ' ', ' '},
    {' ', 'X', ' '},
    {' ', ' ', 'O'}
};

4.1 Worked Example: Matrix Multiplication

Problem: Multiply two 2x2 matrices. Code:

#include <stdio.h>
int main() {
    int A[2][2] = {{1, 2}, {3, 4}};
    int B[2][2] = {{5, 6}, {7, 8}};
    int C[2][2] = {0};

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    printf("Result:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", C[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output:

Result:
19 22
43 50

Trace:

  • C[0][0] = (1*5) + (2*7) = 5 + 14 = 19
  • C[0][1] = (1*6) + (2*8) = 6 + 16 = 22
  • ... and so on.

Real-World Tie-In: Google Maps uses 2D arrays (or more complex data structures) to represent grid-based maps. When calculating the shortest path between two points, the system may treat the map as a matrix where each cell represents a location, and algorithms like Dijkstra’s (see below) are applied to find the optimal route.


5. Searching Algorithms: Finding Data Efficiently

Algorithm Time Complexity Requirement
Linear Search O(n) Unsorted data
Binary Search O(log n) Sorted data

5.1 Binary Search: Divide and Conquer

Problem: Search for 22 in sortedArr = {10, 20, 22, 30, 40}. Code:

int binarySearch(int arr[], int size, int key) {
    int left = 0, right = size - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == key) return mid;
        else if (arr[mid] < key) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

Trace Table:

Step left right mid arr[mid] Condition (arr[mid] == key) Action
1 0 4 2 22 True Return 2

Visualization (Steps):

100201222303404
Binary search for key=22 (mid=2, arr[mid]=22 → found)

Real-World Tie-In: Daraz uses binary search in its product catalog to quickly locate items. For example, if a user searches for a product priced Rs. 1500, the system first checks the middle of the sorted price list. If the middle price is Rs. 1000, it narrows the search to the higher half, reducing the search time from O(n) to O(log n).


6. Pointers and Arrays: The Hidden Connection

Arrays decay into pointers to their first element.

int arr[3] = {10, 20, 30};
int *ptr = arr; // ptr points to arr[0]
printf("%d", *(ptr + 1)); // Output: 20 (arr[1])

Key Insight:

  • arr[i] is equivalent to *(arr + i).
  • Pointer arithmetic enables flexible array manipulation.

7. Common Pitfalls and Best Practices

Pitfall Solution
Array Index Out of Bounds Always check i < size in loops.
Uninitialized Strings Use char str[10] = ""; or strcpy().
Forgetting Null Terminator Ensure strings end with \0.
Incorrect Loop Limits Use for (i=0; i<n; i++) for arrays.

In the Real World

  1. Pathao’s Order Queue:

    • Uses an array or linked list to manage pending orders.
    • When a rider accepts an order, the system removes that element (like dequeue()), shifting remaining elements left (O(n) time for arrays).
    • Example: If orders are stored as ["Order1", "Order2", "Order3"], accepting "Order2" leaves ["Order1", "Order3"].
  2. eSewa’s Transaction Validation:

    • Uses string functions (strcmp(), strlen()) to validate:
      • Phone numbers (must be 10 digits).
      • Transaction IDs (must match a specific format).
    • Example:
      if (strlen(userPhone) != 10) {
          printf("Invalid phone number!");
      }
      
  3. NTC’s Traffic Route Optimization:

    • Represents road networks as 2D arrays (adjacency matrices) where:
      • Rows/columns = intersections.
      • Values = travel time between intersections.
    • Uses Dijkstra’s algorithm (see below) to find the shortest path for emergency vehicles.

Exam Tip

  1. Arrays vs. Strings:

    • Arrays can store any data type (int, float).
    • Strings are character arrays with special functions (strlen(), strcpy()).
    • Exam Question: "Write a program to reverse a string." → Use a loop and swap characters.
  2. Sorting Algorithms:

    • Know Bubble Sort, Selection Sort, and their time complexities.
    • Exam Question: "Sort an array of 5 elements using Bubble Sort." → Show all passes in your answer.
  3. Matrix Operations:

    • Practice matrix addition, multiplication, and transpose.
    • Exam Question: "Multiply two 3x3 matrices." → Write nested loops and explain each step.
  4. Pointers and Arrays:

    • Understand that arr[i] is *(arr + i).
    • Exam Question: "Write a function to print array elements using pointers." → Use *(arr + i).
  5. Common Mistakes:

    • Forgetting array size in loops → Always declare size separately.
    • Not null-terminating strings → Use '\0' explicitly.
    • Off-by-one errors → Start loops from 0 and end at size-1.

Final Note: Arrays and strings are fundamental in C. Master their operations, sorting/searching algorithms, and real-world applications (like order queues or text processing) to excel in exams and practical programming. Always visualize memory layouts and trace code step-by-step to avoid errors.

Based on the TU BITM syllabus for Structured Programming in C (ITM102), unit 4.

Discussion

Loading…