Dremendo Tag Line

Input numbers in 2d array and swap the largest with the smallest number in C

Two Dimensional Array - Question 4

In this question, we will see how to input numbers in a 3X3 integer matrix (2d array) and interchange the largest with the smallest number from it in C programming. To know more about two dimensional array click on the two dimensional array lesson.

Q4) Write a program in C to input numbers in a 3X3 integer matrix (2d array) and interchange the largest with the smallest number from it.

Program

#include <stdio.h>
#include <conio.h>

int main()
{
    int a[3][3], r,c,lg=0,lr,lc,sm=0,sr,sc;

    printf("Enter 9 numbers\n");
    for(r=0; r<3; r++)
    {
        for(c=0; c<3; c++)
        {
            scanf("%d",&a[r][c]);
            if(r==0 && c==0)
            {
                lg=a[r][c];
                lr=r;
                lc=c;
                sm=a[r][c];
                sr=r;
                sc=c;
            }
            else if(a[r][c]>lg)
            {
                lg=a[r][c];
                lr=r;
                lc=c;
            }
            else if(a[r][c]<sm)
            {
                sm=a[r][c];
                sr=r;
                sc=c;
            }
        }
    }

    a[lr][lc]=sm;
    a[sr][sc]=lg;

    printf("\nArray after interchanging largest with the smallest number\n");
    for(r=0; r<3; r++)
    {
        for(c=0; c<3; c++)
        {
            printf("%d ",a[r][c]);
        }
        printf("\n");
    }
    return 0;
}

Output

Enter 9 numbers
5
12
18
2
17
23
45
96
62

Array after interchanging largest with the smallest number
5 12 18
96 17 23
45 2 62
video-poster