Lab Experiment 5

Arrays in C Programming

Course: C Programming | Semester: BTech First | Instructor: Dr. Mohsin Dar

Learning Objectives

  • Understand the concept and implementation of single-dimensional arrays
  • Learn to find second largest element in an array
  • Implement array analysis for positive, negative, odd, and even numbers
  • Calculate frequency of elements in an array
  • Master two-dimensional arrays and matrix operations
  • Implement matrix multiplication with compatibility checking

What are Arrays?

Arrays are collections of elements of the same data type stored in contiguous memory locations. They provide a way to store multiple values under a single variable name and access them using indices.

Syntax: datatype arrayName[size];

Problem 1: Finding Second Largest Element

Write a program to read integers into an array and find the second largest element.

Algorithm:

  1. Initialize largest and second_largest to the first element
  2. Traverse the array starting from the second element
  3. If current element > largest, update second_largest = largest, largest = current
  4. Else if current element > second_largest and current ≠ largest, update second_largest
  5. Return second_largest

Complete Program:

#include <stdio.h>
#include <limits.h>

int findSecondLargest(int arr[], int n) {
    int largest, secondLargest;
    
    // Handle edge cases
    if (n < 2) {
        printf("Array should have at least 2 elements.\n");
        return -1;
    }
    
    // Initialize with first element
    largest = secondLargest = arr[0];
    
    // Find largest and second largest
    for (int i = 1; i < n; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] != largest) {
            secondLargest = arr[i];
        }
    }
    
    // Check if second largest exists
    if (secondLargest == largest) {
        printf("All elements are same. No second largest.\n");
        return -1;
    }
    
    return secondLargest;
}

void printArray(int arr[], int n) {
    printf("Array elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int n, secondLargest;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    
    printArray(arr, n);
    
    secondLargest = findSecondLargest(arr, n);
    
    if (secondLargest != -1) {
        printf("Second largest element: %d\n", secondLargest);
    }
    
    return 0;
}

Sample Output:

Enter the number of elements: 6
Enter 6 integers:
Element 1: 12
Element 2: 35
Element 3: 1
Element 4: 10
Element 5: 34
Element 6: 1
Array elements: 12 35 1 10 34 1 
Second largest element: 34

Problem 2: Count Positive, Negative, Odd, and Even Numbers

Write a program to analyze an array and count different types of numbers.

Complete Program:

#include <stdio.h>

void analyzeArray(int arr[], int n) {
    int positive = 0, negative = 0, zero = 0;
    int even = 0, odd = 0;
    
    printf("\nArray Analysis:\n");
    printf("===============\n");
    
    for (int i = 0; i < n; i++) {
        // Count positive, negative, and zero
        if (arr[i] > 0) {
            positive++;
        } else if (arr[i] < 0) {
            negative++;
        } else {
            zero++;
        }
        
        // Count even and odd
        if (arr[i] % 2 == 0) {
            even++;
        } else {
            odd++;
        }
    }
    
    printf("Positive numbers: %d\n", positive);
    printf("Negative numbers: %d\n", negative);
    printf("Zero: %d\n", zero);
    printf("Even numbers: %d\n", even);
    printf("Odd numbers: %d\n", odd);
}

void displayDetailedAnalysis(int arr[], int n) {
    printf("\nDetailed Analysis:\n");
    printf("==================\n");
    
    printf("Positive numbers: ");
    for (int i = 0; i < n; i++) {
        if (arr[i] > 0) {
            printf("%d ", arr[i]);
        }
    }
    printf("\n");
    
    printf("Negative numbers: ");
    for (int i = 0; i < n; i++) {
        if (arr[i] < 0) {
            printf("%d ", arr[i]);
        }
    }
    printf("\n");
    
    printf("Even numbers: ");
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0) {
            printf("%d ", arr[i]);
        }
    }
    printf("\n");
    
    printf("Odd numbers: ");
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 != 0) {
            printf("%d ", arr[i]);
        }
    }
    printf("\n");
}

int main() {
    int n;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    
    printf("Array elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    analyzeArray(arr, n);
    displayDetailedAnalysis(arr, n);
    
    return 0;
}

Sample Output:

Enter the number of elements: 8
Enter 8 integers:
Element 1: 12
Element 2: -5
Element 3: 0
Element 4: 7
Element 5: -3
Element 6: 14
Element 7: 9
Element 8: -8
Array elements: 12 -5 0 7 -3 14 9 -8 

Array Analysis:
===============
Positive numbers: 4
Negative numbers: 3
Zero: 1
Even numbers: 4
Odd numbers: 4

Detailed Analysis:
==================
Positive numbers: 12 7 14 9 
Negative numbers: -5 -3 -8 
Even numbers: 12 0 14 -8 
Odd numbers: -5 7 -3 9

Problem 3: Finding Frequency of Elements

Write a program to count the frequency of a particular number in an array.

Complete Program:

#include <stdio.h>

int findFrequency(int arr[], int n, int target) {
    int frequency = 0;
    
    printf("Positions of %d in array: ", target);
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            frequency++;
            printf("%d ", i);
        }
    }
    
    if (frequency == 0) {
        printf("Not found");
    }
    printf("\n");
    
    return frequency;
}

void findAllFrequencies(int arr[], int n) {
    int visited[n];
    
    // Initialize visited array
    for (int i = 0; i < n; i++) {
        visited[i] = 0;
    }
    
    printf("\nFrequency of all elements:\n");
    printf("==========================\n");
    
    for (int i = 0; i < n; i++) {
        if (visited[i] == 0) {
            int count = 1;
            
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                    visited[j] = 1;
                }
            }
            
            printf("Element %d appears %d time(s)\n", arr[i], count);
        }
    }
}

int main() {
    int n, target, frequency;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    
    printf("Array elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    printf("Enter the number to find frequency: ");
    scanf("%d", &target);
    
    frequency = findFrequency(arr, n, target);
    printf("Frequency of %d: %d\n", target, frequency);
    
    // Show frequency of all elements
    findAllFrequencies(arr, n);
    
    return 0;
}

Sample Output:

Enter the number of elements: 10
Enter 10 integers:
Element 1: 1
Element 2: 2
Element 3: 1
Element 4: 3
Element 5: 2
Element 6: 1
Element 7: 4
Element 8: 2
Element 9: 1
Element 10: 3
Array elements: 1 2 1 3 2 1 4 2 1 3 
Enter the number to find frequency: 1
Positions of 1 in array: 0 2 5 8 
Frequency of 1: 4

Frequency of all elements:
==========================
Element 1 appears 4 time(s)
Element 2 appears 3 time(s)
Element 3 appears 2 time(s)
Element 4 appears 1 time(s)

Problem 4: Matrix Multiplication

Write a program to multiply two matrices with compatibility checking.

Matrix Multiplication Rules:

  • Matrix A (m×n) can be multiplied with Matrix B (p×q) only if n = p
  • Resultant matrix C will be of size (m×q)
  • C[i][j] = Σ(A[i][k] * B[k][j]) for k = 0 to n-1

Complete Program:

#include <stdio.h>

void inputMatrix(int matrix[][100], int rows, int cols, char name) {
    printf("Enter elements of Matrix %c (%dx%d):\n", name, rows, cols);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Element [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
}

void displayMatrix(int matrix[][100], int rows, int cols, char name) {
    printf("\nMatrix %c (%dx%d):\n", name, rows, cols);
    printf("==================\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%6d ", matrix[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

int multiplyMatrices(int A[][100], int B[][100], int C[][100], 
                      int m, int n, int p, int q) {
    // Check compatibility for multiplication
    if (n != p) {
        printf("Error: Matrix multiplication not possible!\n");
        printf("Number of columns in Matrix A (%d) must equal ", n);
        printf("number of rows in Matrix B (%d)\n", p);
        return 0; // Not compatible
    }
    
    printf("Matrices are compatible for multiplication.\n");
    printf("Resultant matrix will be %dx%d\n\n", m, q);
    
    // Initialize result matrix
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < q; j++) {
            C[i][j] = 0;
        }
    }
    
    // Perform matrix multiplication
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < q; j++) {
            for (int k = 0; k < n; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    
    return 1; // Successfully multiplied
}

void showMultiplicationProcess(int A[][100], int B[][100], 
                              int C[][100], int m, int n, int q) {
    printf("Matrix Multiplication Process:\n");
    printf("==============================\n");
    
    for (int i = 0; i < m && i < 2; i++) {
        for (int j = 0; j < q && j < 2; j++) {
            printf("C[%d][%d] = ", i, j);
            for (int k = 0; k < n; k++) {
                if (k > 0) printf(" + ");
                printf("(%d×%d)", A[i][k], B[k][j]);
            }
            printf(" = %d\n", C[i][j]);
        }
    }
    printf("...\n\n");
}

int main() {
    int A[100][100], B[100][100], C[100][100];
    int m, n, p, q;
    
    printf("Matrix Multiplication Program\n");
    printf("=============================\n\n");
    
    // Input dimensions for Matrix A
    printf("Enter dimensions of Matrix A:\n");
    printf("Rows (m): ");
    scanf("%d", &m);
    printf("Columns (n): ");
    scanf("%d", &n);
    
    // Input dimensions for Matrix B
    printf("Enter dimensions of Matrix B:\n");
    printf("Rows (p): ");
    scanf("%d", &p);
    printf("Columns (q): ");
    scanf("%d", &q);
    
    // Input matrices
    printf("\n");
    inputMatrix(A, m, n, 'A');
    printf("\n");
    inputMatrix(B, p, q, 'B');
    
    // Display input matrices
    displayMatrix(A, m, n, 'A');
    displayMatrix(B, p, q, 'B');
    
    // Attempt multiplication
    if (multiplyMatrices(A, B, C, m, n, p, q)) {
        // Show multiplication process (for small matrices)
        if (m <= 3 && q <= 3) {
            showMultiplicationProcess(A, B, C, m, n, q);
        }
        
        // Display result matrix
        displayMatrix(C, m, q, 'C');
        
        printf("Matrix multiplication completed successfully!\n");
    }
    
    return 0;
}

Sample Output (Compatible Matrices):

Matrix Multiplication Program
=============================

Enter dimensions of Matrix A:
Rows (m): 2
Columns (n): 3
Enter dimensions of Matrix B:
Rows (p): 3
Columns (q): 2

Enter elements of Matrix A (2x3):
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6

Enter elements of Matrix B (3x2):
Element [0][0]: 7
Element [0][1]: 8
Element [1][0]: 9
Element [1][1]: 10
Element [2][0]: 11
Element [2][1]: 12

Matrix A (2x3):
==================
     1      2      3 
     4      5      6 

Matrix B (3x2):
==================
     7      8 
     9     10 
    11     12 

Matrices are compatible for multiplication.
Resultant matrix will be 2x2

Matrix Multiplication Process:
==============================
C[0][0] = (1×7) + (2×9) + (3×11) = 58
C[0][1] = (1×8) + (2×10) + (3×12) = 64
C[1][0] = (4×7) + (5×9) + (6×11) = 139
C[1][1] = (4×8) + (5×10) + (6×12) = 154
...

Matrix C (2x2):
==================
    58     64 
   139    154 

Matrix multiplication completed successfully!

Sample Output (Incompatible Matrices):

Matrix Multiplication Program
=============================

Enter dimensions of Matrix A:
Rows (m): 2
Columns (n): 3
Enter dimensions of Matrix B:
Rows (p): 2
Columns (q): 4

Enter elements of Matrix A (2x3):
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6

Enter elements of Matrix B (2x4):
Element [0][0]: 7
Element [0][1]: 8
Element [0][2]: 9
Element [0][3]: 10
Element [1][0]: 11
Element [1][1]: 12
Element [1][2]: 13
Element [1][3]: 14

Matrix A (2x3):
==================
     1      2      3 
     4      5      6 

Matrix B (2x4):
==================
     7      8      9     10 
    11     12     13     14 

Error: Matrix multiplication not possible!
Number of columns in Matrix A (3) must equal number of rows in Matrix B (2)

Array Concepts Summary

Concept Description Time Complexity Space Complexity
Array Declaration int arr[size] O(1) O(n)
Element Access arr[index] O(1) O(1)
Linear Search Find element in array O(n) O(1)
Finding Second Largest Two-pass algorithm O(n) O(1)
Matrix Multiplication Triple nested loops O(m×n×q) O(m×q)

Additional Examples and Variations

Enhanced Second Largest (Handle Duplicates)

int findSecondLargestUnique(int arr[], int n) {
    int first = INT_MIN, second = INT_MIN;
    
    for (int i = 0; i < n; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] < first) {
            second = arr[i];
        }
    }
    
    return (second == INT_MIN) ? -1 : second;
}

Matrix Addition Function

void addMatrices(int A[][100], int B[][100], int C[][100], 
                int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }
}

Matrix Transpose Function

void transposeMatrix(int matrix[][100], int transpose[][100], 
                    int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
}

Lab Assignment Questions

Practice Questions:

  1. Array Analysis: Modify the second program to also find the sum and average of positive and negative numbers separately.
  2. Matrix Operations: Implement matrix subtraction and addition functions with appropriate error checking.
  3. Advanced Array: Write a program to find the third largest element in an array without sorting.
  4. Frequency Analysis: Create a program that finds the element with the highest frequency in an array.
  5. Matrix Challenge: Implement a function to check if a matrix is symmetric.
Common Mistakes to Avoid:
  • Array index out of bounds access
  • Not checking matrix compatibility before multiplication
  • Forgetting to initialize result matrices to zero
  • Not handling edge cases (empty arrays, single elements)
  • Incorrect loop bounds in nested loops

Key Takeaways

  • Arrays provide efficient storage for multiple elements of the same type
  • Index-based access allows constant-time element retrieval
  • Algorithm efficiency is crucial for array operations
  • Matrix operations follow specific mathematical rules
  • Error handling is essential for robust array programs
  • Memory management understanding helps optimize array usage