Search code examples
cmatrixcomparestore

Storing matrix colum sums and comparing them to find the largest


How do I store 1,2,3...n columns sums to a variable and than compare them to find the largest sum?

#include <stdio.h>
#include <math.h>
#define NUM_ITEMS 1000

int array[NUM_ITEMS];

int main(){
    FILE* file;
    int a[10][10];
    int i,j, count = 0;
    int n=0;

    file = fopen("Matrica.txt", "r");

    while(count < NUM_ITEMS && fscanf(file, "%d", &array[count]) == 1)
        count++;

    n = sqrt(count);

    printf("Dimenzije matrice: %dx%d ",n,n);

    rewind(file);
    for(i=0;i<n;i++)
    for(j=0;j<n;j++){
        fscanf(file,"%d",&a[i][j]);
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("\nElementi matrice: %d \n",a[i][j]);
        }
    }

    int col[n];

    for(j=0;j<n;j++){
        for(i=0;i<n;i++){
            col[i] += a[i][0];
        }
    }
    printf("\nDBG:%d",col[0]);
    fclose(file);  
}

The task is to find dimensions of a[10][10], print out the elements of it and find the column that has biggest sum. What is the name for this var in English. So far I've finished 2/3rds of the task.

Below is the code:

for(j=0;j<n;j++){
        for(i=0;i<n;i++){
            col[i] += a[i][0];
        }
    }

it is the code for calculating sum of the 1st column.

I don't know how to implement it to do what I want, because col[i] must have NULL values for sum to take it's place or it will just print out a bunch a jibberish.

Note: col[0] was supposed to present column 1 , col[1] column 2 etc.


Solution

  • If I guessed correctly from the example you get only one 10x10 matrix from file, and now you want to sum elements in columns(vertically) not in rows(horizontally) try changing

    col[i] += a[i][0] 
    

    to

    col[i] += a[j][i]
    

    Because with your code you were only adding first element of every row. First [] indicates row,second [] indicates column. What this slight change does is it sums every column element of row to its column index in col[i]. Because I don't know how your text file looks like I suppose you for sure get 10x10 matrix with valid elements.