Functions – Matrix Maximum

Functions – Matrix Maximum

Write a program to find the maximum element in a matrix using functions.

Function specification:

int findMax(int **a, int m, int n)
The first argument corresponds to the pointer to the matrix.
The second argument corresponds to the number of rows in the matrix.
The third argument corresponds to the number of columns in the matrix.


Input and Output Format:
Assume that the maximum number of rows and columns in the matrix is 10.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output :
Enter the number of rows in the matrix
3
Enter the number of columns in the matrix
2
Enter the elements of the matrix
2
4
1
3
5
9
The matrix is
2 4
1 3
5 9
The maximum element in the matrix is 9



Function Definitions: 

int findMax (int **a, int m, int n) 

Image result for c coding

Solution:

#include <  stdio.h  >
#include<  stdlib.h  >
int findMax(int**a,int m,int n)
{
    int max,i,j;
    max=a[0][0];
    for(i=0; i  <  m ;  i++)
    for(j=0;j  <  n;j++)
    if(a[i][j]  >  max)
    max=a[i][j];
    return max;
}
int main()
{
    int n,m,i,j,maxt;
    printf("Enter the number of rows in the matrix\n");
    scanf("%d",&n);
    printf("Enter the number of columns in the matrix\n");
    scanf("%d",&m);
    printf("Enter the elements in the matrix\n");
    int **a=(int **)malloc(n*sizeof(int *));
    for(i=0;i  <  n;i++)
    a[i]=(int *)malloc(m*sizeof(int));
    for(i=0;i  <  n;i++)
    for(j=0;j  <  m;j++)
    {
        scanf("%d",&a[i][j]);
        maxt=findMax(a,n,m);
    }
    printf("The matrix is\n");
    for(i=0;i  <  n;i++)
    {
        for(j=0;j  <  m;j++)
        printf("%d ",a[i][j]);
        printf("\n");
    }
    printf("The maximum element in the matrix is %d",maxt);
    return 0;

}

No comments