ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C program to arrange column elements in ascending order

Here, we are going to learn how to arrange column elements in ascending order in C programming language?
Submitted by Nidhi, on July 14, 2021

Problem Solution:

Given a matrix, we have to arrange column elements in ascending order using C program.

Program:

The source code to arrange column elements in ascending order is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to arrange column elements in ascending order

#include <stdio.h>

#define ROW 3
#define COL 3

int main()
{

    int Matrix[ROW][COL] = {
        { 9, 8, 7 },
        { 5, 4, 6 },
        { 1, 2, 3 }
    };

    int i, j, k, temp;

    printf("Matrix:\n");
    for (i = 0; i < ROW; ++i) {
        for (j = 0; j < COL; ++j)
            printf(" %d", Matrix[i][j]);
        printf("\n");
    }

    // Arrange columns elements in ascending order
    for (j = 0; j < COL; ++j) {
        for (i = 0; i < ROW; ++i) {
            for (k = i + 1; k < ROW; ++k) {
                if (Matrix[i][j] > Matrix[k][j]) {
                    temp = Matrix[i][j];
                    Matrix[i][j] = Matrix[k][j];
                    Matrix[k][j] = temp;
                }
            }
        }
    }

    printf("Matrix after sorting column elements:\n");
    for (i = 0; i < ROW; ++i) {
        for (j = 0; j < COL; ++j)
            printf(" %d", Matrix[i][j]);
        printf("\n");
    }

    return 0;
}

Output:

Matrix:
 9 8 7
 5 4 6
 1 2 3
Matrix after sorting column elements:
 1 2 3
 5 4 6
 9 8 7

Explanation:

Here, we created a 3X3 matrix matrix using the 2D array. Then we sorted the column elements and printed the updated matrix on the console screen.

C Two-dimensional Arrays Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.