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,990 questions

51,935 answers

573 users

How to sum 2D array (matrix) cols in C

1 Answer

0 votes
#include <stdio.h>
         
void sum_matrix_cols(int matrix[][5], int cols_sum[3], int rows, int cols)
{
    for (int j = 0; j < cols; j++) {
        for (int i = 0; i < rows; i++)
            cols_sum[j] += matrix[i][j];
    }
}
  
int main()
{
    int matrix[3][5] = { { 1, 2, 3, 4, 5 },
                         { 1, 2, 3, 4, 5 },
                         { 1, 2, 3, 4, 5 } };
  
    int cols_sum[5] = { 0 };
    int rows = sizeof matrix / sizeof matrix[0];
    int cols = sizeof matrix[0] / sizeof(int);
  
    sum_matrix_cols(matrix, cols_sum, rows, cols);
  
    for (int i = 0; i < 5; i++)
        printf("%d\n", cols_sum[i]);
  
    return 0;
}
 
/*
run:
 
3
6
9
12
15
 
*/

 



answered Apr 13, 2018 by avibootz
edited Apr 13, 2018 by avibootz

Related questions

1 answer 118 views
118 views asked Apr 12, 2018 by avibootz
1 answer 175 views
175 views asked Apr 18, 2018 by avibootz
1 answer 148 views
1 answer 154 views
154 views asked Apr 18, 2018 by avibootz
1 answer 180 views
180 views asked Apr 18, 2018 by avibootz
2 answers 192 views
1 answer 112 views
112 views asked Apr 13, 2018 by avibootz
...