×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to arrange row elements in ascending order

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

Problem statement

Given an array, we have to arrange the row elements in ascending order using C program.

Arranging row elements in ascending order

The source code to arrange row 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 row elements in ascending order

// C program to arrange row elements in ascending order

#include <stdio.h>
#define ROW 3
#define COL 3

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

    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 rows elements in ascending order
    for (i = 0; i < ROW; ++i) {
        for (j = 0; j < COL; ++j) {
            for (k = (j + 1); k < COL; ++k) {
                if (Matrix[i][j] > Matrix[i][k]) {
                    temp = Matrix[i][j];
                    Matrix[i][j] = Matrix[i][k];
                    Matrix[i][k] = temp;
                }
            }
        }
    }

    printf("Matrix after sorting row 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:
 3 2 1
 5 4 6
 9 8 7
Matrix after sorting row elements:
 1 2 3
 4 5 6
 7 8 9

Explanation

In the main() function, we created a 3X3 matrix matrix using the 2D array. Then we sorted the elements of the rows and printed the updated matrix on the console screen.

C Two-dimensional Arrays Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.