C Program To Find the Largest Element in a Row in 2d Array

In this tutorial, i am going to show you how to find the maximum or largest element in each row on 2d array in c program..

C Program and Algorithm To Find the Largest Element in a Row in 2d Array

  • Algorithm To Find the Largest Element in Each Row in 2d Array
  • C Program To Find the Largest Element in Each Row in 2d Array

Algorithm To Find the Largest Element in Each Row in 2d Array

Just use the below given algorithm to write a program to find the maximum element in each row of the 2d array or matrix array; as follows:

  1. Start
  2. Declare a 2D array.
  3. Initialize the 2D array.
  4. Take input row and column count from user.
  5. Take input 2d array elements from user.
  6. Iterate the for loop to total number of rows.
  7. Check each element for the row and find the maximum element from it.
  8. Now print the elements.
  9. Stop.

C Program To Find the Largest Element in Each Row in 2d Array

#include <stdio.h>
int main()
{
    int m,n;                 //Matrix Size Declaration
    printf("Enter the number of rows and column: \n");
    scanf("%d %d",&m,&n);   //Matrix Size Initialization
    int arr[10][10];        //Matrix Size Declaration
    printf("\nEnter the elements of the matrix: \n");
    for(int i=0;i<m;i++)    //Matrix Initialization
    {
        for(int j=0;j<n;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    printf("\nThe elements in the matrix are: \n");
    for(int i=0;i<m;i++)     //Print the matrix
    {
        for(int j=0;j<n;j++)
        {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    int i = 0, j;
    int max = 0;
    int res[m];
    while (i < m)   //Check for the largest element in an array
    {
       for ( j = 0; j < n; j++)
       {
           if (arr[i][j] > max)
           {
              max = arr[i][j];
           }
        }
        res[i] = max;
        max = 0;
        i++;
    }
    for(int i = 0; i < n; i++)      //Print the largest element in an array
    {
       printf("Largest element in row %d is %d \n", i, res[i]);
    }
    
    return 0;
}

The result of the above c program; as follows:

Enter the number of rows and column: 
3 3
Enter the elements of the matrix: 
1 2 3 4 5 6 7 8 9
The elements in the matrix are: 
1 2 3 
4 5 6 
7 8 9 
Largest element in row 0 is 3 
Largest element in row 1 is 6 
Largest element in row 2 is 9 

More C Programming Tutorials

Leave a Comment