Home > other >  Find the column with biggest sum in matrix and print it out
Find the column with biggest sum in matrix and print it out

Time:12-15

I am writing a program that you enter the n rows x m columns matrix, and then find the column with the biggest sum and print that column out,i am trying to print that column out. Any help would be appreciated.

For example:

  Input            Output
4 5 6 4 0 0          4
4 2 3 2 2 2          4
6 5 2 1 0 1          6

My result:

  Input            Output
4 5 6 4 0 0         
4 2 3 2 2 2          14
6 5 2 1 0 1

And there is my code:

#include<stdio.h>
void Entermatrix(int a[][50], int &n,int &m)
{
 printf("Enter matrix's rows: ");
 scanf("%d",&n);
 printf("Enter matrix's columms: ");
 scanf("%d",&m);
    for(int i=0;i<n;i  )
        for(int j=0;j<m;j  ){
            printf("A[%d][%d]= ",i,j);
            scanf("%d",&a[i][j]);
    }
}
void Printmatrix(int a[][50], int n, int m)
{
    for(int i=0;i<n;i  ){
        for(int j=0;j<m;j  ) {
            printf("]",a[i][j]);
   }
    printf("\n");}
}
void Columnwithbiggestsum(int a[][50],int n,int m)
{
    int max=0;
    
    for(int i=0;i<m;i  )
    {
        int sum=0;
        for(int j=0;j<n;j  ){
            sum = sum a[j][i];
        }
        if (sum >max){
            max=sum;
        }   
        }printf ("The biggest sum by column is: %d",max);
}
int main()
{
 int a[50][50],n,m;
 Entermatrix(a,n,m);
 Printmatrix(a,n,m);
 Columnwithbiggestsum(a,n,m);
 return 0;
}

CodePudding user response:

In the function "Columnwithbiggestsum" you can keep another variable to store the Column number with the highest sum.

once you have column number you can Iterate in the matrix to print the content of that column.

Modified your code to print the column

void Columnwithbiggestsum(int a[][50],int n,int m)
{
    int max=0;
    int columnNo=0;
    for(int i=0;i<m;i  )
    {
        int sum=0;
        for(int j=0;j<n;j  ){
            sum = sum a[j][i];
        }
        if (sum >max){
            max=sum;
            columnNo = i;
        }   
    }
   
    for(int i=0;i<n;i  )
    {
        printf ("%d \n", a[i][columnNo]);
    }
}
  • Related