Arrays and Multi-dimensional Arrays

Unit III: Array and Function | Lecture 11

Dr. Mohsin Dar
Assistant Professor, SOCS | UPES
C Programming
BTech First Semester

šŸŽÆ Learning Objectives

By the end of this lecture, you will be able to:

  • Understand the concept and need for arrays in programming
  • Declare, initialize, and access elements of one-dimensional arrays
  • Perform operations on arrays (input, output, searching, sorting)
  • Understand multi-dimensional arrays, especially 2D arrays
  • Work with matrices using 2D arrays
  • Apply array concepts to solve real-world problems

šŸ“Š What is an Array?

An array is a collection of elements of the same data type, stored in contiguous memory locations and accessed using a common name and index.

Key Characteristics:

  • Homogeneous: All elements must be of the same data type
  • Indexed: Elements are accessed using indices (starting from 0)
  • Fixed Size: Size is determined at declaration time
  • Contiguous Memory: Elements are stored in consecutive memory locations
Real-world Example: Think of an array like a row of lockers in a school - each locker has a number (index) and can store items of the same type.

šŸ”§ Array Declaration and Initialization

Syntax: data_type array_name[size];

Declaration Examples:

int numbers[5];        // Array of 5 integers
float grades[10];      // Array of 10 floating-point numbers
char name[20];         // Array of 20 characters (string)
                    

Initialization Methods:

// Method 1: Initialize during declaration
int arr1[5] = {10, 20, 30, 40, 50};

// Method 2: Partial initialization (remaining elements = 0)
int arr2[5] = {10, 20};  // {10, 20, 0, 0, 0}

// Method 3: Size determined by initializer
int arr3[] = {1, 2, 3, 4, 5};  // Size = 5

// Method 4: Initialize all elements to 0
int arr4[5] = {0};
                    

šŸ’¾ Array Memory Representation

Let's visualize how array

int arr[5] = {10, 20, 30, 40, 50}
is stored in memory:

10
arr[0]
20
arr[1]
30
arr[2]
40
arr[3]
50
arr[4]
Important: Array indices start from 0. For an array of size n, valid indices are 0 to n-1.

Memory Address Calculation:

If base address = 1000 and each integer takes 4 bytes:

  • arr[0] → 1000
  • arr[1] → 1004
  • arr[2] → 1008
  • arr[3] → 1012
  • arr[4] → 1016

⚔ Basic Array Operations

1. Input and Output:

#include <stdio.h>

int main() {
    int arr[5];
    int i;
    
    // Input elements
    printf("Enter 5 integers: ");
    for(i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Output elements
    printf("Array elements: ");
    for(i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}
                    

2. Finding Maximum Element:

int findMax(int arr[], int size) {
    int max = arr[0];
    for(int i = 1; i < size; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}
                    

šŸ”¢ Multi-dimensional Arrays

A multi-dimensional array is an array of arrays. The most common is the 2D array, which can be thought of as a table with rows and columns.

2D Array Declaration:

data_type array_name[rows][columns];
// Examples of 2D array declaration
int matrix[3][4];        // 3 rows, 4 columns
float grades[5][3];      // 5 students, 3 subjects
char board[3][3];        // 3x3 tic-tac-toe board
                    

2D Array Initialization:

            // Method 1: Row-wise initialization
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

// Method 2: Linear initialization
int matrix[2][3] = {1, 2, 3, 4, 5, 6};

// Method 3: Partial initialization
int matrix[2][3] = {{1, 2}, {4}};  // Remaining elements = 0
                    

šŸŽØ 2D Array Visualization

Let's visualize a 2D array: int matrix[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}

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

Accessing Elements:

  • matrix[0][0] = 1 (first row, first column)
  • matrix[1][2] = 7 (second row, third column)
  • matrix[2][3] = 12 (third row, fourth column)
Remember: Both row and column indices start from 0!

šŸ”„ 2D Array Operations

1. Input and Output:

#include <stdio.h>

int main() {
    int matrix[3][3];
    int i, j;
    
    // Input elements
    printf("Enter elements of 3x3 matrix:\n");
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Output elements
    printf("\nMatrix:\n");
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}
                    

āž• Matrix Operations

Matrix Addition:

   
// Function to add two matrices
void addMatrices(int a[][3], int b[][3], int result[][3], int rows, int cols) {
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            result[i][j] = a[i][j] + b[i][j];
        }
    }
}
                    

Matrix Multiplication:

// Function to multiply two matrices
void multiplyMatrices(int a[][3], int b[][3], int result[][3], int r1, int c1, int c2) {
    for(int i = 0; i < r1; i++) {
        for(int j = 0; j < c2; j++) {
            result[i][j] = 0;
            for(int k = 0; k < c1; k++) {
                result[i][j] += a[i][k] * b[k][j];
            }
        }
}
}
                    
Note: For matrix multiplication AƗB, the number of columns in A must equal the number of rows in B.

🌟 Practical Applications

Arrays are used in:

  • Student Management: Storing grades, roll numbers
  • Image Processing: 2D arrays represent pixel values
  • Game Development: Game boards, maps, inventories
  • Mathematical Computing: Vectors, matrices, statistics
  • Data Analysis: Storing and processing large datasets

Real Example: Student Grade Management

// 2D array: 5 students, 3 subjects
float grades[5][3] = {
    {85.5, 92.0, 78.5},  // Student 1
    {90.0, 87.5, 95.0},  // Student 2
    {78.0, 82.5, 88.0},  // Student 3
    {92.5, 89.0, 91.5},  // Student 4
    {87.0, 85.5, 90.0}   // Student 5
};

// Calculate average for each student
for(int i = 0; i < 5; i++) {
    float sum = 0;
    for(int j = 0; j < 3; j++) {
        sum += grades[i][j];
    }
    printf("Student %d average: %.2f\n", i+1, sum/3);
}
                        

āš ļø Common Pitfalls & Best Practices

Common Mistakes:

  • Array Bounds: Accessing arr[5] in an array of size 5
  • Uninitialized Arrays: Using array elements without initialization
  • Wrong Index: Starting loops from 1 instead of 0
  • Size Confusion: Forgetting array size in function parameters

Best Practices:

  • Always initialize arrays before use
  • Use meaningful variable names
  • Check array bounds in loops
  • Use constants for array sizes
  • Document your array usage
// Good practice: Use constants
#define MAX_STUDENTS 50
#define MAX_SUBJECTS 5

int grades[MAX_STUDENTS][MAX_SUBJECTS];

// Good practice: Bounds checking
if(index >= 0 && index < MAX_STUDENTS) {
    // Safe to access grades[index]
}
                    

šŸ“‹ Summary

Key Concepts Covered:

  • Arrays: Collections of similar data types
  • Indexing: Zero-based indexing for element access
  • 1D Arrays: Linear collections with single dimension
  • 2D Arrays: Matrix-like structures with rows and columns
  • Operations: Input/output, searching, mathematical operations
  • Applications: Data management, mathematical computing, games

Next Lecture Preview:

Lecture 12: Functions in C Programming

  • Function declaration and definition
  • Parameter passing (call by value, call by reference)
  • Arrays as function parameters
  • Recursive functions

Thank you for your attention! šŸŽ“

Questions and discussions are welcome!