Home > Mobile >  Sum of a specific column in 2D array in C
Sum of a specific column in 2D array in C

Time:11-09

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.

CodePudding user response:

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].

  • Related