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.

40,023 questions

51,974 answers

573 users

How to get max row and calculate the sum of max row in 2D array of integers in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

#define ROW 3
#define COL 4

void print(size_t arr[][COL], size_t row, size_t col);
void randomArr2D(size_t arr[][COL], size_t row, size_t col);
size_t sumRow(size_t arr[][COL], size_t row, size_t col);
 
int main(int argc, char **argv) 
{
    size_t arr[ROW][COL], i, sum, max = 0, max_row;
  
    randomArr2D(arr, ROW, COL);
    print(arr, ROW, COL);
    
    for (i = 0; i < ROW; i++)
    {
        sum = sumRow(arr, i, COL);
        if (sum > max)
        {
            max = sum;
            max_row = i;
        }
    }
    
    printf("max row = %d sum of max row = %d", max_row, max);
  
    return 0;
}
size_t sumRow(size_t arr[][COL], size_t row, size_t col)
{
    size_t j, sum = 0;;
    
    for (j = 0; j < col; j++)
        sum += arr[row][j];
    
    return sum;
}
void print(size_t arr[][COL], size_t row, size_t col)
{
    size_t i, j;

    for (i = 0; i < row; i++) 
    {
         for (j = 0; j < col; j++) 
            printf("%3d", arr[i][j]);
            
        printf("\n");
    }
}
void randomArr2D(size_t arr[][COL], size_t row, size_t col)
{
    size_t i, j;
    
    srand(time(NULL));
    for (i = 0; i < row; i++) 
         for (j = 0; j < col; j++) 
            arr[i][j] = rand() % 10 + 1;
}
/*
run:

  3  9  5  3
 10  7  5  3
  6 10  8  6
max row = 2 sum of max row = 30

*/


answered Apr 6, 2015 by avibootz
...