This blog is under construction

Saturday 29 June 2013

C program to find the minimum and maximum value of each column in a given matrix

Write a C program to find the minimum and maximum value of each column in a given matrix.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int row, col, **data, i, j, min, max;

        /* get the number of rows and column from the user */
        printf("Enter the no of rows and columns:");
        scanf("%d%d", &row, &col);

        /* dynamically allocate memory to store array entries */
        data = (int **)malloc(sizeof (int) * row);
        for (i = 0; i < col; i++)
                data[i] = (int *)malloc(sizeof (int) * col);

        /* get the inputs entries */
        printf("Enter your inputs:");
        for (i = 0; i < row; i++)
                for (j = 0; j < col; j++)
                        scanf("%d", &data[i][j]);

        /* find the min and max element in each column */
        for (i = 0; i < col; i++) {
                min = data[0][i];
                max = data[0][i];
                for (j = 0; j < row; j++) {
                        if (data[j][i] < min)
                                min = data[j][i];
                        if (data[j][i] > max)
                                max = data[j][i];
                }
                printf("Column %d: Max: %d Min:%d\n", i+1, max, min);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the no of rows and columns:3 3
  Enter your inputs:
  10 20 30
  40 50 60
  15 25 35
  Column 1: Max: 40 Min:10
  Column 2: Max: 50 Min:20
  Column 3: Max: 60 Min:30



No comments:

Post a Comment