12 June, 2013

C++ Program For Sorting All Elements Of A Matrix.

This Post Contains A C++ Program For Sorting All Elements Of A Matrix With Correct Source Code, Algorithm & Output. This Program Is Written, Compiled & Executed At Turbo C/C++3.0 Compiler & Will Help You To Understand The Concept Of 'Arrays', 'For-Loop', 'If...else' & 'Nested Loops' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.


# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.



C++ Program For Sorting All Elements Of A Matrix.
/* Declaration Of Header Files */
#include <iostream.h>
#include <conio.h>

/* Start Of Main Program */
void main()
{

/* Declaration Of Variables */
int a[10][10], b[30], i, j, r, c, s, t;

clrscr();

/* Asking For The Input From User */
cout  <<  "  Enter Number Of Rows & Columns Of 2D Array [ Matrix ]  :  ";
cin  >>  r  >>  c ;

      

//  Accepting Values Of 2D Array [ Matrix ]
cout  <<  "  Enter  "  <<  r  *  c  <<  "  Values for 2D Array  :  ";
t=0;
for  (  i  =  0;  i  <  r;  i++  )
{

      for  (  j  =  0;  j  <  c;  j++  )

     {

            cin  >>  a [ i ][ j ];

            b[t]=a[i][j];

            t++

     }
}

/* Source Code For Sorting All Elements Of A Matrix */
for(i=0; i < t; i++)
{

      for(j=i+1; j b[j])

           s=b[i];

           b[i]=b[j];

           b[j]=s;

      }
}

cout  <<  " \n Elements Of Matrix A : ";
for(i=0; i < r; i++)
{

      cout  <<  "\n";

      for(j=0; j < c; j++)

      {

         cout  <<  a[i][j]  <<  "\t";

      }
}

/* Assigning Sorted Elements */
t=0;
for(i=0; i < r; i++)
{

      for(j=0; j < c; j++)

      {

         a[i][j]=b[t];

         t++;

      }
}

/* Printing The Output Onto The Screen/Console */
cout  <<  " \n After Sorting Elements Of Matrix A : ";
for(i=0; i < r; i++)
{

      cout  <<  "\n";

      for(j=0; j < c; j++)

      {

         cout  <<  a[i][j]  <<  "\t";

      }
}

getch();

}
/* End Of Main Program */

Output:
Enter Order For Array A : 3 3

Enter 9 Values For Array :

1  2  3  4  5  6  7  8  9

Array A Is :

1  4  9

2  7  8

5  6  3

After Sorting Elements Of Matrix A :

1  2  3

4  5  6

7  8  9




No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.

Blog Archive