Chapter 8: Arrays

📌 Learning Objectives
  • LO 8.1: Understand the concept of arrays as derived data types
  • LO 8.2: Work with one-dimensional arrays
  • LO 8.3: Implement two-dimensional arrays
  • LO 8.4: Handle multi-dimensional arrays
  • LO 8.5: Understand dynamic arrays
  • LO 8.6: Perform searching and sorting on arrays

8.1 Introduction to Arrays

An array is a fixed-size sequenced collection of elements of the same data type. It is a derived data type that allows efficient storing, accessing, and manipulation of large volumes of data.

Examples where arrays are useful:

📌 Data Structures in C:

Arrays and structures are referred to as structured data types because they can be used to represent data values that have a structure of some sort. In programming parlance, such data types are known as data structures.

8.2 One-Dimensional Arrays

A list of items can be given one variable name, and the individual elements can be accessed by their index or subscript.

Declaration of One-Dimensional Arrays

data_type array_name[size];

Examples:

int marks[50];
float height[50];
char name[30];
Example: int number[5] = {35, 40, 20, 57, 19};

Memory representation:

Index:   0     1     2     3     4
      +-----+-----+-----+-----+-----+
      | 35  | 40  | 20  | 57  | 19  |
      +-----+-----+-----+-----+-----+
Address: 1000  1002  1004  1006  1008  (assuming 2 bytes per int)

Initialization of One-Dimensional Arrays

Compile-time initialization:

int number[5] = {35, 40, 20, 57, 19};
int counter[] = {1, 1, 1, 1};  // size automatically determined
float total[5] = {0.0, 15.75, -10};  // remaining elements set to 0
char name[] = {'J', 'o', 'h', 'n', '\0'};
char name[] = "John";  // string initialization

Run-time initialization:

int x[5];
for (i = 0; i < 5; i++)
    scanf("%d", &x[i]);

📝 Worked-Out Problem 8.1

Program to illustrate one-dimensional array:

#include <stdio.h>

int main() {
    int i;
    float x[10], value, total = 0;
    
    printf("Enter 10 real numbers:\n");
    for (i = 0; i < 10; i++) {
        scanf("%f", &value);
        x[i] = value;
    }
    
    for (i = 0; i < 10; i++)
        total += x[i] * x[i];
    
    printf("Sum of squares = %f\n", total);
    return 0;
}
Output:
Enter 10 real numbers:
1 2 3 4 5 6 7 8 9 10
Sum of squares = 385.000000

📝 Worked-Out Problem 8.2

Frequency counting using arrays:

#include <stdio.h>
#define COUNTER 11

int main() {
    int group[COUNTER] = {0};
    int i, value;
    
    printf("Enter marks (0-100), -1 to end:\n");
    scanf("%d", &value);
    
    while (value != -1) {
        if (value >= 0 && value <= 100)
            group[value/10]++;
        scanf("%d", &value);
    }
    
    printf("\nGROUP    RANGE    FREQUENCY\n");
    for (i = 0; i < COUNTER; i++) {
        if (i == 10)
            printf("%2d       100      %d\n", i, group[i]);
        else
            printf("%2d       %2d-%3d   %d\n", i, i*10, i*10+9, group[i]);
    }
    
    return 0;
}
Output:
Enter marks (0-100), -1 to end:
45 67 23 89 12 78 56 91 34 82 -1

GROUP RANGE FREQUENCY
0 0- 9 0
1 10- 19 1
2 20- 29 1
3 30- 39 1
4 40- 49 1
5 50- 59 1
6 60- 69 1
7 70- 79 1
8 80- 89 2
9 90- 99 1
10 100 0

8.3 Two-Dimensional Arrays

Two-dimensional arrays are used to represent tables of data consisting of rows and columns.

Declaration of Two-Dimensional Arrays

data_type array_name[row_size][column_size];

Example:

int matrix[4][3];  // 4 rows, 3 columns
Table: Sales data (4 salesgirls × 3 items)

        Item 1  Item 2  Item 3
Girl 1    310     275     365
Girl 2    210     190     325
Girl 3    405     235     240
Girl 4    260     300     380

In C: int sales[4][3] = {
    {310, 275, 365},
    {210, 190, 325},
    {405, 235, 240},
    {260, 300, 380}
};

Initialization of Two-Dimensional Arrays

int table[2][3] = {0, 0, 0, 1, 1, 1};  // row-wise initialization
int table[2][3] = {{0, 0, 0}, {1, 1, 1}};  // with braces
int matrix[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

📝 Worked-Out Problem 8.3

Program to print multiplication table using two-dimensional array:

#include <stdio.h>
#define ROWS 5
#define COLS 5

int main() {
    int product[ROWS][COLS];
    int i, j;
    
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            product[i][j] = (i+1) * (j+1);
        }
    }
    
    printf("Multiplication Table:\n");
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("%5d", product[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}
Output:
Multiplication Table:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

📝 Worked-Out Problem 8.4

Program to tabulate survey data (cars per city):

#include <stdio.h>
#define CITIES 5
#define TYPES 5

int main() {
    int frequency[CITIES][TYPES] = {{0}};
    int city, type, i, j;
    
    printf("Enter city code (1-5) and car type (1-5), 0 to end:\n");
    scanf("%d %d", &city, &type);
    
    while (city != 0 && type != 0) {
        if (city >= 1 && city <= CITIES && type >= 1 && type <= TYPES)
            frequency[city-1][type-1]++;
        scanf("%d %d", &city, &type);
    }
    
    printf("\nFrequency Table:\n");
    printf("City\\Type");
    for (i = 1; i <= TYPES; i++)
        printf("%4d", i);
    printf("\n");
    
    for (i = 0; i < CITIES; i++) {
        printf("%4d    ", i+1);
        for (j = 0; j < TYPES; j++)
            printf("%4d", frequency[i][j]);
        printf("\n");
    }
    
    return 0;
}

8.4 Multi-Dimensional Arrays

C allows arrays of three or more dimensions. The general form is:

data_type array_name[size1][size2][size3]...[sizeN];

Examples:

int survey[3][5][12];  // 3 years, 5 cities, 12 months
float table[5][4][5][3];  // 4-dimensional array

Storage order: The rightmost subscript varies fastest (row-major order).

A 2×3×3 array is stored as:

[0][0][0], [0][0][1], [0][0][2],
[0][1][0], [0][1][1], [0][1][2],
[0][2][0], [0][2][1], [0][2][2],
[1][0][0], [1][0][1], [1][0][2],
[1][1][0], [1][1][1], [1][1][2],
[1][2][0], [1][2][1], [1][2][2]

📝 Worked-Out Problem 8.5

Program to find transpose of a matrix:

#include <stdio.h>
#define ROWS 3
#define COLS 4

int main() {
    int matrix[ROWS][COLS] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    int transpose[COLS][ROWS];
    int i, j;
    
    // Compute transpose
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
    
    printf("Original Matrix:\n");
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++)
            printf("%4d", matrix[i][j]);
        printf("\n");
    }
    
    printf("\nTranspose Matrix:\n");
    for (i = 0; i < COLS; i++) {
        for (j = 0; j < ROWS; j++)
            printf("%4d", transpose[i][j]);
        printf("\n");
    }
    
    return 0;
}
Output:
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12

Transpose Matrix:
1 5 9
2 6 10
3 7 11
4 8 12

📝 Worked-Out Problem 8.6

Program for N×N matrix multiplication:

#include <stdio.h>
#define N 3

int main() {
    int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int B[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    int C[N][N] = {{0}};
    int i, j, k;
    
    // Matrix multiplication: C = A × B
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            for (k = 0; k < N; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    
    printf("Resultant Matrix:\n");
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            printf("%4d", C[i][j]);
        printf("\n");
    }
    
    return 0;
}
Output:
Resultant Matrix:
30 24 18
84 69 54
138 114 90

8.5 Dynamic Arrays

Arrays created at compile time have fixed size. C allows dynamic memory allocation at run time using functions from <stdlib.h>.

Memory Allocation Functions

FunctionPurpose
malloc(size)Allocates a block of size bytes
calloc(n, size)Allocates space for n elements of size bytes each, initialized to 0
realloc(ptr, new_size)Changes size of previously allocated memory
free(ptr)Frees previously allocated memory
#include <stdlib.h>

int *arr;
arr = (int *)malloc(10 * sizeof(int));  // allocate array of 10 integers
if (arr == NULL) {
    printf("Memory allocation failed!\n");
    exit(1);
}

// Use the array...

free(arr);  // free memory when done

8.6 Searching and Sorting

Linear Search

Searches for an element by checking each position sequentially.

📝 Worked-Out Problem 8.7

Linear search implementation:

#include <stdio.h>

int linear_search(int arr[], int size, int key) {
    int i;
    for (i = 0; i < size; i++) {
        if (arr[i] == key)
            return i;  // return position if found
    }
    return -1;  // return -1 if not found
}

int main() {
    int arr[100], n, key, i, position;
    
    printf("Enter the size of the list: ");
    scanf("%d", &n);
    
    printf("Enter the elements:\n");
    for (i = 0; i < n; i++) {
        printf("arr[%d] = ", i);
        scanf("%d", &arr[i]);
    }
    
    printf("Enter the data to be searched: ");
    scanf("%d", &key);
    
    position = linear_search(arr, n, key);
    
    if (position != -1)
        printf("Data %d found at position %d\n", key, position);
    else
        printf("Data %d not found in the array\n", key);
    
    return 0;
}
Output:
Enter the size of the list: 5
Enter the elements:
arr[0] = 50
arr[1] = 30
arr[2] = 10
arr[3] = 60
arr[4] = 80
Enter the data to be searched: 60
Data 60 found at position 3

Bubble Sort

Repeatedly steps through the list, compares adjacent elements and swaps them if they're in the wrong order.

📝 Worked-Out Problem 8.8

Bubble sort implementation:

#include <stdio.h>

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

int main() {
    int arr[100], n, i;
    
    printf("Enter the size of the list: ");
    scanf("%d", &n);
    
    printf("Enter the elements:\n");
    for (i = 0; i < n; i++) {
        printf("arr[%d] = ", i);
        scanf("%d", &arr[i]);
    }
    
    bubble_sort(arr, n);
    
    printf("Sorted list:\n");
    for (i = 0; i < n; i++)
        printf("arr[%d] = %d\n", i, arr[i]);
    
    return 0;
}
Output:
Enter the size of the list: 5
Enter the elements:
arr[0] = 64
arr[1] = 34
arr[2] = 25
arr[3] = 12
arr[4] = 22
Sorted list:
arr[0] = 12
arr[1] = 22
arr[2] = 25
arr[3] = 34
arr[4] = 64

Selection Sort

Finds the minimum element and places it at the beginning, then repeats for the remaining elements.

📝 Worked-Out Problem 8.9

Selection sort implementation:

#include <stdio.h>

void selection_sort(int arr[], int n) {
    int i, j, min_idx, temp;
    
    for (i = 0; i < n-1; i++) {
        min_idx = i;
        for (j = i+1; j < n; j++) {
            if (arr[j] < arr[min_idx])
                min_idx = j;
        }
        
        if (min_idx != i) {
            temp = arr[i];
            arr[i] = arr[min_idx];
            arr[min_idx] = temp;
        }
    }
}

int main() {
    int arr[100], n, i;
    
    printf("Enter the size of the list: ");
    scanf("%d", &n);
    
    printf("Enter the elements:\n");
    for (i = 0; i < n; i++) {
        printf("arr[%d] = ", i);
        scanf("%d", &arr[i]);
    }
    
    selection_sort(arr, n);
    
    printf("Sorted list:\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

Important Points About Arrays

  • Array indices start at 0 and end at size-1.
  • C performs no bounds checking - accessing outside array bounds leads to unpredictable results.
  • The array name represents the address of the first element.
  • When passing arrays to functions, only the address is passed (call by reference).
  • Strings are character arrays terminated by null character '\0'.

Chapter Exercises

Review Questions

  1. State true or false:
    a) An array can store infinite data of similar type.
    b) The declaration int x[2] = {1,2,3}; is illegal.
    c) When an array is declared, C automatically initializes its elements to zero.
    d) An expression that evaluates to an integral value may be used as a subscript.
    e) Accessing an array outside its range is a compile-time error.
  2. What is a data structure? Why is an array called a data structure?
  3. What happens when an array with a specified size is assigned:
    a) values fewer than the specified size
    b) values more than the specified size
  4. Write a for loop that initializes all diagonal elements of a 5×5 matrix to 1 and others to 0.

Multiple Choice Questions

  1. How many integer values can the array N[5][5] store?
    a) 10
    b) 25
    c) 16
    d) 24
  2. What index value should be used to access the last element of the integer array N[10]?
    a) 10
    b) 9
    c) 11
    d) None
  3. The process of creating a fixed-sized array by allocating memory at compile time is called:
    a) Static memory allocation
    b) Dynamic memory allocation
    c) Run-time memory allocation
    d) None
  4. An array N[3] = {1,2,3} is declared. What will be the output of printf("%d", N[3]);?
    a) 3
    b) 2
    c) 4
    d) Garbage value

Debugging Exercises

Identify errors in the following array declarations:

int score (100);
float values [10,15];
char name[15];
float average[ROW][COLUMN];  // ROW and COLUMN are constants
int sum[ ];
int array x[10];

Find errors in initialization statements:

int number[ ] = {0,0,0,0,0};
float item[3][2] = {0,1,2,3,4,5};
char word[ ] = {'A','R','R','A','Y'};
int m[2,4] = {(0,0,0,0)(1,1,1,1)};
float result[10] = 0;

Programming Exercises

  1. Write a program to find the median of a list of numbers. (Sort the list and find the middle value)
  2. Write a program to calculate the standard deviation of n numbers.
  3. Write a program to evaluate a multiple-choice test. The program should read correct answers and student responses, then count correct answers.
  4. Write a program for production and sales analysis using two-dimensional arrays.
  5. Write a program to read two matrices A and B and print their sum and difference.
  6. Write a program to read two sorted arrays and merge them into a third sorted array.
  7. Write a program to implement binary search on a sorted array.
  8. Write a program to print Pascal's triangle for 10 rows.
  9. Write a program to read a matrix of size m×n and print its transpose.
  10. Write a program to check if a given ISBN number is valid. (ISBN: 10-digit number with check digit)

Interview Questions

  1. What is the difference between null array and empty array?
  2. What is the difference between malloc and calloc?
  3. What will be the output of:
    int arr[5] = {1,2,3,4,5};
    printf("%d", arr[5]);
  4. How can you find the number of elements in an array without using sizeof?
  5. What is the difference between array and linked list?

Case Study: Median of a List of Numbers

📝 Case Study: Finding Median

#include <stdio.h>

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

float find_median(int arr[], int n) {
    sort(arr, n);
    
    if (n % 2 == 1)
        return arr[n/2];
    else
        return (arr[n/2 - 1] + arr[n/2]) / 2.0;
}

int main() {
    int arr[100], n, i;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    
    printf("Median = %.2f\n", find_median(arr, n));
    
    return 0;
}
Output:
Enter the number of elements: 5
Enter 5 numbers:
45 23 67 12 89
Median = 45.00

Case Study 2: Standard Deviation

📝 Case Study: Calculating Standard Deviation

#include <stdio.h>
#include <math.h>

float mean(float arr[], int n) {
    float sum = 0;
    int i;
    for (i = 0; i < n; i++)
        sum += arr[i];
    return sum / n;
}

float std_dev(float arr[], int n) {
    float m = mean(arr, n);
    float sum = 0;
    int i;
    
    for (i = 0; i < n; i++)
        sum += (arr[i] - m) * (arr[i] - m);
    
    return sqrt(sum / n);
}

int main() {
    float data[100];
    int n, i;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++)
        scanf("%f", &data[i]);
    
    printf("Mean = %.2f\n", mean(data, n));
    printf("Standard Deviation = %.2f\n", std_dev(data, n));
    
    return 0;
}
Output:
Enter the number of elements: 5
Enter 5 numbers:
10 20 30 40 50
Mean = 30.00
Standard Deviation = 14.14