Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

C Language Array and Matrix Operations Lab

Tools 1

1. One-Dimensional and Two-Dimensional Array Memory Layout Test

This test verifies the memory storage of one-dimensional and two-dimensional int arrays.

#include <stdio.h>
#define ARRAY_SIZE 4
#define ROW_COUNT 2

void testOneDArray() {
    int arr[ARRAY_SIZE] = {1, 9, 8, 4};
    int idx;
    printf("Size of one-dimensional array: %lu bytes\n", sizeof(arr));
    for (idx = 0; idx < ARRAY_SIZE; ++idx)
        printf("%p: %d\n", &arr[idx], arr[idx]);
    printf("Array name address: %p\n", arr);
}

void testTwoDArray() {
    int mat[ROW_COUNT][ARRAY_SIZE] = {{1, 9, 8, 4}, {2, 0, 4, 9}};
    int row, col;
    printf("Size of two-dimensional array: %lu bytes\n", sizeof(mat));
    for (row = 0; row < ROW_COUNT; ++row)
        for (col = 0; col < ARRAY_SIZE; ++col)
            printf("%p: %d\n", &mat[row][col], mat[row][col]);
    printf("\nArray name address: %p\n", mat);
    printf("First row address: %p\n", mat[0]);
    printf("Second row address: %p\n\n", mat[1]);
}

int main() {
    printf("=== One-Dimensional Array Test ===\n");
    testOneDArray();
    printf("\n=== Two-Dimensional Array Test ===\n");
    testTwoDArray();
    return 0;
}

Elements in one-dimensional arrays are stored continuous, and the array name points to the first element's address. Two-dimensional arrays are stored row-wise, with each row's elements contiguous, and consecutive rows separated by 16 bytes (since ARRAY_SIZE * sizeof(int) = 4*4=16).

2. Calculate Trimmed Mean (Excluding Max and Min)

This program reads an array of integers, excludes the maximum and minimum values, and calculates the average of the remaining elements.

#include <stdio.h>
#define MAX_ELEMENTS 100

void readArray(int arr[], int count) {
    int idx;
    for (idx = 0; idx < count; ++idx)
        scanf("%d", &arr[idx]);
}

double calculateTrimmedMean(int arr[], int count) {
    int idx, maxVal, minVal;
    double sum = 0;
    maxVal = minVal = arr[0];
    for (idx = 0; idx < count; ++idx) {
        sum += arr[idx];
        if (arr[idx] > maxVal)
            maxVal = arr[idx];
        else if (arr[idx] < minVal)
            minVal = arr[idx];
    }
    return (sum - maxVal - minVal) / (count - 2);
}

int main() {
    int arr[MAX_ELEMENTS];
    int count;
    double result;
    while (printf("Enter count: "), scanf("%d", &count) != EOF) {
        readArray(arr, count);
        result = calculateTrimmedMean(arr, count);
        printf("Trimmed mean: %.2f\n\n", result);
    }
    return 0;
}

3. Initialize and Print Square Matrix

This program initializes an n×n square matrix with a specified value and prints it.

#include <stdio.h>
#define MAX_DIM 100

void initializeMatrix(int mat[][MAX_DIM], int size, int value) {
    int row, col;
    for (row = 0; row < size; ++row)
        for (col = 0; col < size; ++col)
            mat[row][col] = value;
}

void printMatrix(int mat[][MAX_DIM], int size) {
    int row, col;
    for (row = 0; row < size; ++row) {
        for (col = 0; col < size; ++col)
            printf("%d ", mat[row][col]);
        printf("\n");
    }
}

int main() {
    int mat[MAX_DIM][MAX_DIM];
    int size, val;
    while (printf("Enter size and value: "), scanf("%d%d", &size, &val) != EOF) {
        initializeMatrix(mat, size, val);
        printMatrix(mat, size);
        printf("\n");
    }
    return 0;
}

4. Calculate Median of an Array

This program reads an array, sorts it using bubble sort, and calculates the median.

#include <stdio.h>
#define MAX_ELEMENTS 100

void readArray(int arr[], int count) {
    for (int idx = 0; idx < count; idx++)
        scanf("%d", &arr[idx]);
}

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

double getMedian(int arr[], int count) {
    bubbleSortArray(arr, count);
    if (count % 2 == 1)
        return (double)arr[count / 2];
    else
        return (double)(arr[count / 2 - 1] + arr[count / 2]) / 2;
}

int main() {
    int arr[MAX_ELEMENTS];
    int count;
    double median;
    while (printf("Enter count: "), scanf("%d", &count) != EOF) {
        readArray(arr, count);
        median = getMedian(arr, count);
        printf("Median: %g\n\n", median);
    }
    return 0;
}

5. Rotate Square Matrix Right by One Column

This program rotates an n×n square matrix right by one colum.

#include <stdio.h>
#define MAX_DIM 100

void readMatrix(int mat[][MAX_DIM], int size) {
    int row, col;
    for (row = 0; row < size; ++row)
        for (col = 0; col < size; ++col)
            scanf("%d", &mat[row][col]);
}

void printMatrix(int mat[][MAX_DIM], int size) {
    int row, col;
    for (row = 0; row < size; ++row) {
        for (col = 0; col < size; ++col)
            printf("%4d", mat[row][col]);
        printf("\n");
    }
}

void rotateRight(int mat[][MAX_DIM], int size) {
    int row, col, temp;
    for (row = 0; row < size; row++) {
        temp = mat[row][size - 1];
        for (col = size - 1; col > 0; col--)
            mat[row][col] = mat[row][col - 1];
        mat[row][0] = temp;
    }
}

int main() {
    int mat[MAX_DIM][MAX_DIM];
    int size;
    printf("Enter size: ");
    scanf("%d", &size);
    readMatrix(mat, size);
    printf("Original matrix:\n");
    printMatrix(mat, size);
    rotateRight(mat, size);
    printf("Rotated matrix:\n");
    printMatrix(mat, size);
    return 0;
}

6. Convert Decimal to Binary, Octal, and Hexadecimal

This program converts a decimal integer to binary, octal, and hexadecimall.

#include <stdio.h>
#define MAX_DIGITS 20

void decimalToBase(int num, int base) {
    int remainders[MAX_DIGITS], len = 0;
    while (num != 0) {
        remainders[len] = num % base;
        num /= base;
        len++;
    }
    for (int i = len - 1; i >= 0; i--) {
        if (remainders[i] >= 10 && base == 16)
            printf("%c", remainders[i] - 10 + 'A');
        else
            printf("%d", remainders[i]);
    }
    printf("\n");
}

int main() {
    int num;
    while (printf("Enter decimal number: "), scanf("%d", &num) != EOF) {
        printf("Binary: ");
        decimalToBase(num, 2);
        printf("Octal: ");
        decimalToBase(num, 8);
        printf("Hexadecimal: ");
        decimalToBase(num, 16);
        printf("\n");
    }
    return 0;
}

7. Check if a Square Matrix is a Magic Square

This program checks if an n×n square matrix is a magic square (all rows, columns, and diagonals have the same sum).

#include <stdio.h>
#define MAX_DIM 100

void readMatrix(int mat[][MAX_DIM], int size) {
    int row, col;
    for (row = 0; row < size; ++row)
        for (col = 0; col < size; ++col)
            scanf("%d", &mat[row][col]);
}

void printMatrix(int mat[][MAX_DIM], int size) {
    int row, col;
    for (row = 0; row < size; ++row) {
        for (col = 0; col < size; ++col)
            printf("%4d", mat[row][col]);
        printf("\n");
    }
}

int isMagicSquare(int mat[][MAX_DIM], int size) {
    int expectedSum = 0, currentSum = 0;
    for (int i = 0; i < size; i++)
        expectedSum += mat[0][i];
    for (int i = 0; i < size; i++) {
        currentSum = 0;
        for (int j = 0; j < size; j++)
            currentSum += mat[i][j];
        if (currentSum != expectedSum)
            return 0;
    }
    for (int i = 0; i < size; i++) {
        currentSum = 0;
        for (int j = 0; j < size; j++)
            currentSum += mat[j][i];
        if (currentSum != expectedSum)
            return 0;
    }
    currentSum = 0;
    for (int i = 0; i < size; i++)
        currentSum += mat[i][i];
    if (currentSum != expectedSum)
        return 0;
    currentSum = 0;
    for (int i = 0; i < size; i++)
        currentSum += mat[i][size - 1 - i];
    return currentSum == expectedSum;
}

int main() {
    int mat[MAX_DIM][MAX_DIM];
    int size;
    while (printf("Enter size: "), scanf("%d", &size) != EOF) {
        printf("Enter matrix:\n");
        readMatrix(mat, size);
        printf("Matrix:\n");
        printMatrix(mat, size);
        if (isMagicSquare(mat, size))
            printf("This is a magic square.\n\n");
        else
            printf("This is not a magic square.\n\n");
    }
    return 0;
}

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.