Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C Programming Exercises on Arrays, Matrix Operations, and Number Base Conversion

Tech May 8 4

1D and 2D Integer Array Memory Layout Analysis

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

void analyze_single_dim() {
    int values[COLS] = {1, 9, 8, 4};
    int idx;
    printf("Total size of values: %lu bytes\n", sizeof(values));
    for (idx = 0; idx < COLS; idx++)
        printf("Address %p holds %d\n", &values[idx], values[idx]);
    printf("Base address of values: %p\n", values);
}

void analyze_double_dim() {
    int matrix[ROWS][COLS] = {{1, 9, 8, 4}, {2, 0, 4, 9}};
    int r, c;
    printf("Total size of matrix: %lu bytes\n", sizeof(matrix));
    for (r = 0; r < ROWS; r++)
        for (c = 0; c < COLS; c++)
            printf("Address %p holds %d\n", &matrix[r][c], matrix[r][c]);
    printf("\n");
    printf("Matrix base address: %p\n", matrix);
    printf("First row address: %p\n", matrix[0]);
    printf("Second row address: %p\n", matrix[1]);
}

int main() {
    printf("Analysis 1: Single Dimension Integer Array\n");
    analyze_single_dim();
    printf("\nAnalysis 2: Two Dimension Integer Array\n");
    analyze_double_dim();
    return 0;
}

Observations:

  • Memory addresses of array elements are contiguous, confirming linear storage.
  • The base address matrix matches matrix[0] because both point to the start of the first row.
  • The difference between matrix[1] and matrix[0] is 16 bytes, which equals COLS * sizeof(int) (4 elements * 4 bytes).

Average Calculation Excluding Min and Max

#include <stdio.h>
#define MAX_SIZE 100
void read_scores(int arr[], int count);
double calc_average(int arr[], int count);

int main() {
    int scores[MAX_SIZE];
    int count;
    double result;

    while (printf("Input count: "), scanf("%d", &count) != EOF) {
        read_scores(scores, count);
        result = calc_average(scores, count);
        printf("Final Average: %.2f\n\n", result);
    }
    return 0;
}

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

double calc_average(int arr[], int count) {
    int i, min_val, max_val;
    double sum = 0;

    min_val = max_val = arr[0];
    for (i = 0; i < count; i++) {
        sum += arr[i];
        if (arr[i] > max_val) max_val = arr[i];
        else if (arr[i] < min_val) min_val = arr[i];
    }
    return (sum - max_val - min_val) / (count - 2);
}

Implementation Notes:

  • Function parameter int arr[] accepts the array passed from main (e.g., int scores[MAX_SIZE]).
  • read_scores handles populating the aray, while calc_average removes the highest and lowest values before computing the mean.

Square Matrix Initialization and Display

#include <stdio.h>
#define DIM 100
void display_matrix(int mat[][DIM], int size);
void fill_matrix(int mat[][DIM], int size, int val);

int main() {
    int grid[DIM][DIM];
    int size, val;
    while (printf("Input size and value: "), scanf("%d%d", &size, &val) != EOF) {
        fill_matrix(grid, size, val);
        display_matrix(grid, size);
        printf("\n");
    }
    return 0;
}

void display_matrix(int mat[][DIM], int size) {
    int r, c;
    for (r = 0; r < size; r++) {
        for (c = 0; c < size; c++)
            printf("%d ", mat[r][c]);
        printf("\n");
    }
}

void fill_matrix(int mat[][DIM], int size, int val) {
    int r, c;
    for (r = 0; r < size; r++)
        for (c = 0; c < size; c++)
            mat[r][c] = val;
}

Implementation Notes:

  • The functon parameter int mat[][DIM] is compatible with the actual argument int grid[DIM][DIM].
  • fill_matrix sets every cell to the specified value, and display_matrix prints the resulting square grid.

Median Calculation with Bubble Sort

#include <stdio.h>
#define MAX 100
void read_data(int arr[], int count);
double find_median(int arr[], int count);
void bubble_sort(int arr[], int count);

int main() {
    int data[MAX];
    int count;
    double median;
    while (printf("Input count: "), scanf("%d", &count) != EOF) {
        read_data(data, count);
        median = find_median(data, count);
        printf("Median = %g\n\n", median);
    }
    return 0;
}

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

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

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

Matrix Column Rotation to the Right

#include <stdio.h>
#define SIZE 100
void read_matrix(int mat[][SIZE], int n);
void print_matrix(int mat[][SIZE], int n);
void rotate_right(int mat[][SIZE], int n);

int main() {
    int mat[SIZE][SIZE];
    int n;

    printf("Enter dimension: ");
    scanf("%d", &n);
    read_matrix(mat, n);

    printf("Original Matrix:\n");
    print_matrix(mat, n);

    rotate_right(mat, n);

    printf("Rotated Matrix:\n");
    print_matrix(mat, n);
    return 0;
}

void read_matrix(int mat[][SIZE], int n) {
    int i, j;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &mat[i][j]);
}

void print_matrix(int mat[][SIZE], int n) {
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            printf("%4d", mat[i][j]);
        printf("\n");
    }
}

void rotate_right(int mat[][SIZE], int n) {
    int last_col[SIZE];
    for (int i = 0; i < n; i++)
        last_col[i] = mat[i][n - 1];

    for (int col = n - 1; col > 0; col--)
        for (int row = 0; row < n; row++)
            mat[row][col] = mat[row][col - 1];

    for (int i = 0; i < n; i++)
        mat[i][0] = last_col[i];
}

Decimal to Binary, Octal, and Hexadecimal Conversion

#include <stdio.h>
#define BUF 100
void convert_base(int num, int base);

int main() {
    int decimal;
    while (printf("Enter decimal integer: "), scanf("%d", &decimal) != EOF) {
        convert_base(decimal, 2);
        convert_base(decimal, 8);
        convert_base(decimal, 16);
        printf("\n");
    }
    return 0;
}

void convert_base(int num, int base) {
    int digits[BUF], idx = 0;
    while (num > 0) {
        digits[idx++] = num % base;
        num /= base;
    }
    for (int i = idx - 1; i >= 0; i--)
        printf("%d", digits[i]);
    printf("\n");
}

Magic Square Verification

#include <stdio.h>
#define MAX_DIM 100
void input_square(int sq[][MAX_DIM], int n);
void output_square(int sq[][MAX_DIM], int n);
int check_magic(int sq[][MAX_DIM], int n);

int main() {
    int sq[MAX_DIM][MAX_DIM];
    int n;
    while (printf("Enter dimension: "), scanf("%d", &n) != EOF) {
        printf("Input the square:\n");
        input_square(sq, n);
        printf("Display:\n");
        output_square(sq, n);
        if (check_magic(sq, n))
            printf("Is a magic square\n\n");
        else
            printf("Not a magic square\n\n");
    }
    return 0;
}

void input_square(int sq[][MAX_DIM], int n) {
    int i, j;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &sq[i][j]);
}

void output_square(int sq[][MAX_DIM], int n) {
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            printf("%4d", sq[i][j]);
        printf("\n");
    }
}

int check_magic(int sq[][MAX_DIM], int n) {
    int target = n * (n * n + 1) / 2;
    int exists[MAX_DIM * MAX_DIM + 1] = {0};

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int val = sq[i][j];
            if (val < 1 || val > n * n || exists[val])
                return 0;
            exists[val] = 1;
        }
    }

    for (int i = 0; i < n; i++) {
        int row_sum = 0;
        for (int j = 0; j < n; j++)
            row_sum += sq[i][j];
        if (row_sum != target) return 0;
    }

    for (int j = 0; j < n; j++) {
        int col_sum = 0;
        for (int i = 0; i < n; i++)
            col_sum += sq[i][j];
        if (col_sum != target) return 0;
    }

    int diag1 = 0, diag2 = 0;
    for (int i = 0; i < n; i++) {
        diag1 += sq[i][i];
        diag2 += sq[i][n - 1 - i];
    }
    if (diag1 != target || diag2 != target) return 0;

    return 1;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

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