Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of a specific column in 2D array in C

I just want to know how to sum a specific column given the index of its column. I already do the sum, but for all column

#include <stdio.h>

#define LINE 4
#define COLUMN 3

int main()
{
    int arr[LINE][COLUMN] = {
         1,  2,  3,
         4,  5,  6,
         7,  8,  9,
        10, 11, 12 };

    int csum = 0;

    printf("\nColumn Sum....\n");
    for (int i = 0; i < LINE; i++)
    {
        for(int j = 0; j < COLUMN; j++)
        {
            csum = csum + arr[j][i];
            printf("%d | csum: %d \n", i, csum);
        }
    }

    printf("\nSum of all the elements in column is %d\n",csum);

    return 0;
}

I want to give i.e "0" for the column and it returns 22 (1 + 4 + 7 + 10). I tried hardcode the "j" in the in csum = csum + arr[j][i] to csum = csum + arr[0][i] but it doesn’t work.

Thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Get rid of the column loop.

#include <stdio.h>
#define LINE 4
#define COLUMN 3

int main()
{
    int arr[LINE][COLUMN] = {1,2,3,
            4,5,6,
            7,8,9,
            10,11,12};

    int csum = 0;
    int column = 0; // desired column

    printf("\nColumn Sum....\n");
    for(int i = 0 ; i < LINE ; i++)
    {
        csum += arr[i][column];
    }
    printf("\nSum of all the elements in column %d is %d\n", column, csum);

    return 0;
}

You also had the row and column indexes backwards in arr[j][i].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading