Friday, 16 January 2015

Write a program which takes two 4x4 matrix A and B containing 16 elements each and sort all these 32 elements in descending order and put it in one dimensional array and then finally display the ordered array on console as well as write the same array in a file named “sorted.txt”. This process must be repeated three times, which means your txt file will have three sorted arrays in it, indicating the first second and third sorted array separately.


#include<iostream>

#include<fstream>

using namespace std;

int main()

{

    int x=0,k,l,temp=0;            //declare variables..

    int m1[4][4],m2[4][4],sort[32];

  

     for(int p=1;p<=3;p++)//print 3 times on the console and in file...

   {

    cout<<"\t\t*..Enter 1st Matrix values..*\n\n";  //take input of ist matrix values...

    for(int i=0;i<4;i++)

    {

      for(int j=0;j<4;j++)

      {

        cout<<"\t"<<"["<<i+1<<"] ["<<j+1<<"]=\t\t";

        cin>>m1[i][j];

        cout<<endl;

        }

    }

  

    cout<<"\t\t*....Enter 2nd Matrix values.....*\n\n"; ////take input of 2nd matrix values

    for(int i=0;i<4;i++)

    {

      for(int j=0;j<4;j++)

      {

        cout<<"\t"<<"["<<i+1<<"] ["<<j+1<<"]=\t\t";

        cin>>m2[i][j];

        cout<<endl;

        }

    }

  

    for(int i=0;i<4;i++)    //put 1st matrix values into one dimensional array

    {

      for(int j=0;j<4;j++)

      {

       sort[x]=m1[i][j];

       x++;

       }

    }

    cout<<"\n";

  

    for(int i=0;i<4;i++)   //also put 2nd matrix values into one dimensional array

    {

      for(int j=0;j<4;j++)

      {

       sort[x]=m2[i][j];

       x++;

       }

    } 

  

   for( k=0;k<32;k++)    //sorting the one dimensional array into descending order...

   {

    for( l=0;l<31;l++)

    {

      if(sort[l]<sort[l+1])

       { 

         temp=sort[l];

        sort[l]=sort[l+1];

        sort[l+1]=temp;   

      }

   }

}

 //  system("cls");          //clear the previous screen ....

  

   ofstream file;          //declare file ..

   file.open("sorted.txt");//create & open file named sorted.txt..

  



     cout<<"\t\t**...sorted elements in descending order...**\n\n\n" ;

     file<<"\t\t**...sorted elements in descending order...**\n\n\n" ;

      for(int i=0;i<32;i++)

      {

         cout<<sort[i]<<"   ";  //print on console

         file<<sort[i]<<"   ";  //print in the file...

          }

     cout<<"\n\n"; 

     file<<"\n\n";

   }



    system("pause");

    return 0;

    }

0 comments:

Post a Comment