Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to calculate the products of (jagged) uneven-sized matrix columns in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

int* column_products(int** matrix, int* row_lengths, int rows, int* out_cols) {
    // Find the maximum number of columns
    int max_cols = 0;
    for (int i = 0; i < rows; i++) {
        if (row_lengths[i] > max_cols) {
            max_cols = row_lengths[i];
        }
    }

    int* products = malloc(max_cols * sizeof(int));
    if (!products) return NULL;

    // Compute column products
    for (int col = 0; col < max_cols; col++) {
        int product = 1;

        for (int row = 0; row < rows; row++) {
            if (col < row_lengths[row]) {
                product *= matrix[row][col];
            }
        }

        products[col] = product;
    }

    *out_cols = max_cols;
    
    return products;
}

int main(void) {
    // Equivalent to: int[][] matrix = { {1,2,3}, {4,5}, {6,7,8,9} };

    int row0[] = {1, 2, 3};
    int row1[] = {4, 5};
    int row2[] = {6, 7, 8, 9};

    int* matrix[] = { row0, row1, row2 };
    int row_lengths[] = { 3, 2, 4 };
    int rows = 3;

    int cols = 0;
    int* result = column_products(matrix, row_lengths, rows, &cols);

    if (!result) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    printf("Column products: ");
    for (int i = 0; i < cols; i++) {
        printf("%d ", result[i]);
    }

    free(result);
    
    return 0;
}



/*
run:
  
Column products: 24 70 24 9 
  
*/

 



answered 14 hours ago by avibootz
...