Mengkonversi Array 2 dimensi ke 1 dimensi

Konversi ini sama saja dengan konversi array 1 dimensi ke 2 dimensi hanya saja di balik. Berikut code selengkapnya :

#include <cstdlib>
#include <iostream>

using namespace std;
class convert{
      friend istream& operator>>(istream&, convert&); //fungsi input
      friend ostream& operator<<(ostream&, convert&); // fungsi output
             public:
                    convert();
                    void pindah(); // fungsi pindah
             private:
                     int x[100][100],y[100]; //array integer
                     int k,m,n; // variabel integer
                     };
      convert::convert(){ //deskripsi fungsi input
                         cout<<"\tProgram Memindah Array 1 Dimensi Ke 2 Dimensi"<<endl;
                         }
      istream& operator>>(istream& in, convert& a){ // deskripsi fungsi output
               cout<<"Masukkan Baris Array 2 Dimensi :"; in>>a.n;
               cout<<"Masukkan Kolom Array 2 Dimensi :"; in>>a.m;
               for(int i=0; i<a.n; i++){
                   for(int j=0; j<a.m; j++){
                           cout<<"Masukkan data ["<<i+1<<"]["<<j+1<<"]:";
                           in>>a.x[i][j];
                           }}  
               return in;}
      ostream& operator<<(ostream& out, convert& b){ // deskripsi fungsi output
               out<<"Data Array 2 Dimensi :"<<endl;
               for(int i=0; i<b.n; i++){
                   for(int j=0; j<b.m; j++){
                           out<<b.x[i][j]<<"\t"; // menampilkan array 2 dimensi
                           }
                           out<<endl;
                           }
               out<<endl;
               out<<"Data Array Setelah di Pindah :"<<endl;
               for (int i=0; i<(b.n*b.m); i++){
                   out<<b.y[i]; // menampilkan array 1 dimensi
                   }
                   out<<endl;
                           return out;}
      void convert::pindah(){
           k=0;
           for(int i=0; i<n; i++){
                   for(int j=0; j<m; j++){
                           y[k]=x[i][j]; // pemberian nilai
                           k=k+1;
                           }
                           cout<<endl;
                           }
                           }
      
int main(int argc, char *argv[])
{
    convert g;
    cin>>g;
    g.pindah();
    cout<<g;
    system("PAUSE");
    return EXIT_SUCCESS;
}

Hasil Running :

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: