Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

program to swap max and min in matrix

#include <stdio.h>

int main(void)
{
    int rows, cols;
    do
    {
          printf("Give me the number of rows :");
          scanf("%d",&rows);
    }while(rows<1);
    do
    {
          printf("Give me the number of cols :");
          scanf("%d",&cols);
    }while(cols<1);
    int arr[rows][cols];
    printf("
The filling of the Matrix :
");
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            scanf("%d", &arr[i][j]);
        }
    }
    int i_max = 0,j_max=0;
    int i_min = 0,j_min=0;
    int max=arr[0][0];
    int min=arr[0][0];
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            if (arr[i][j]>max)
            {
                max=arr[i][j];
                i_max=i;// i_max mean's the index i of the maximum element
                j_max=j;// j_max mean's the index j of the maximum element
            }
            if(arr[i][j]<min)
            {
                min=arr[i][j];
                i_min=i;// i_max mean's the index i of the minimum element
                j_min=j;// j_max mean's the index j of the minimum element
            }
        }
    }
    printf("
Display of the Matrix before the swap :
");
    for (int i = 0; i < rows; i++)
    {printf("
");
        for (int j = 0; j < cols; j++)
        {
             printf("[%d]", arr[i][j]);
        }
    }

    int temp=arr[i_min][j_min];
    arr[i_min][j_min]=arr[i_max][j_max];
    arr[i_max][j_max]=temp;

    printf("

Display of the Matrix after the swap :
");

    for (int i = 0; i < rows; i++)
    {printf("
");
        for (int j = 0; j < cols; j++)
        {
            printf("[%d]", arr[i][j]);
        }
    }
    return 0;
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #program #swap #max #min #matrix
ADD COMMENT
Topic
Name
8+9 =