Arrays in C

Jul 23, 2024

Lecture Notes: Arrays in C

Introduction

  • Basic data types: char, int, float, double
  • Limitation: Can store only one value at a time
  • Need for handling large volumes of data efficiently
  • Solution: Array

What is an Array?

  • Definition: Fixed-size sequenced collection of elements of the same data type
  • Uses: Convenient for representing lists (e.g., temperatures, employee details, product costs, test scores)

Types of Arrays

  1. One-Dimensional Arrays
  2. Two-Dimensional Arrays
  3. Multi-Dimensional Arrays

One-Dimensional Arrays

  • Syntax: data_type array_name[size];
  • Example: Adding three numbers with variables a, b, c
  • Indexing: Starts from 0
  • Accessing: array_name[index]

Example Code:

int main() {
    int a[10];
    a[0] = 56;
    a[9] = 90;
    // Taking input in a loop
    for (int i = 0; i < 10; i++) {
        scanf("%d", &a[i]);
    }
    // Calculating sum
    int sum = 0;
    for (int i = 0; i < 10; i++) {
        sum += a[i];
    }
    // Calculating average
    float average = (float)sum / 10.0;
    printf("Average: %f", average);
}

Two-Dimensional Arrays

  • Definition: Used to represent tables or matrices
  • Syntax: data_type array_name[rows][columns];
  • Example: Marks of students, matrices representation
  • Indexing: Rows and columns starting from 0

Example Code:

int main() {
    int marks[2][4] = {
        {10, 20, 30, 40},
        {50, 60, 70, 80}
    };
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%d ", marks[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Character Arrays and Strings

  • String: Collection of characters
  • Syntax: char str[length];
  • Initialization:
    • Single character constants: char a[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
    • String constants: char a[10] = "Hello";

Example Code:

int main() {
    char a[10] = "Hello";
    printf("The string is: %s", a);
    return 0;
}

Reading Series of Words using scanf

  • Input: Read multiple strings
  • Output: Display the input strings

Example Code:

int main() {
    char word1[20], word2[20], word3[20], word4[20];
    printf("Enter four words: \n");
    scanf("%s %s %s %s", word1, word2, word3, word4);
    printf("Word1: %s\nWord2: %s\nWord3: %s\nWord4: %s\n", word1, word2, word3, word4);
    return 0;
}

Searching Algorithms

Linear Search

  • Process:
    • Compare each element with the target value
    • Set a flag if found

Example Code:

int main() {
    int a[10], n, key, flag = 0;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    printf("Enter the number to be searched: ");
    scanf("%d", &key);
    for (int i = 0; i < n; i++) {
        if (a[i] == key) {
            flag = 1;
            break;
        }
    }
    if (flag) {
        printf("Number found!");
    } else {
        printf("Number not found!");
    }
    return 0;
}

Binary Search

  • Pre-requisite: Array must be sorted
  • Process:
    • Find mid-point and compare
    • Adjust search range based on comparison

Example Code:

int main() {
    int a[] = {3, 5, 7, 9, 13, 17, 33, 47, 88, 95};
    int key = 17;
    int start = 0, end = 9, mid;
    while (start <= end) {
        mid = (start + end) / 2;
        if (a[mid] == key) {
            printf("Found at %d", mid);
            return 0;
        } else if (a[mid] < key) {
            start = mid + 1;
        } else {
            end = mid - 1;
        }
    }
    printf("Not found");
    return 0;
}

Sorting Algorithms

Selection Sort

  • Process:
    • Select minimum element and swap with first element
    • Move to the next element and repeat

Example Code:

int main() {
    int array[5] = {5, 3, 8, 2, 1};
    int size = 5;
    for (int i = 0; i < size - 1; i++) {
        int min_index = i;
        for (int j = i + 1; j < size; j++) {
            if (array[j] < array[min_index]) {
                min_index = j;
            }
        }
        // Swap
        int temp = array[i];
        array[i] = array[min_index];
        array[min_index] = temp;
    }

    // Print sorted array
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    return 0;
}

Bubble Sort

  • Process:
    • Compare adjacent elements and swap if needed
    • Repeat until array is sorted

Example Code:

int main() {
    int array[5] = {13, 24, 36, 17, 12};
    int size = 5;
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                // Swap
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    // Print sorted array
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    return 0;
}