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.

39,922 questions

51,855 answers

573 users

How to find the largest element of each row in a matrix with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define ROWS 5
#define COLS 6

void printMatrix(int matrix[][COLS]) {
    for (int i = 0; i < ROWS; i++) {  
        for (int j = 0; j < COLS; j++) {
            printf("%4d", matrix[i][j]);
        } 
        printf("\n");
    }
}
  
int generateRandomInteger(int min, int max) {
    return min + rand() / (RAND_MAX / (max - min + 1) + 1);
    // return rand() % (max - min + 1) + min;
}
      
void generateRandomMatrix(int matrix[][COLS]) {
    srand(time(NULL));
     
    for (int i = 0; i < ROWS; i++) {     
        for (int j = 0; j < COLS; j++) {
            matrix[i][j] = generateRandomInteger(1, 100);
        }
    }
}

int getMaxInRow(int matrix[][COLS], int row) {
    int max = matrix[0][0];
    
    for (int j = 0; j < COLS; j++) {
        if (matrix[row][j] > max) {
            max = matrix[row][j];
        }
    }
    
    return max;
}
 
int main() {
    int matrix[ROWS][COLS] = {{ 0 }};
     
    generateRandomMatrix(matrix);
        
    printMatrix(matrix);
    
    for (int i = 0; i < ROWS; i++) {
        printf("\nmax in row %d = %d", i, getMaxInRow(matrix, i));
    }
     
    return 0;
}
 
 
 
 
/*
run:
  
  84  72  42  12  76  23
  96  21  37   6  35  89
  46  84  96  65  73  89
  31  12  62  97  90  96
  82  52  11  85  42  75

max in row 0 = 84
max in row 1 = 96
max in row 2 = 96
max in row 3 = 97
max in row 4 = 85
  
*/

 



answered Nov 12, 2023 by avibootz

Related questions

1 answer 94 views
1 answer 97 views
1 answer 112 views
1 answer 95 views
1 answer 91 views
1 answer 83 views
...