"The best way to cheer yourself up is to try to cheer somebody else up." Mark Twain

Monday, February 1, 2010

From a two-dimensional array A[4][4], write a program to prepare a one-dimensional array B[16], that will have all the elements of A if they are stored in row-major form.

For example, for the following array

                                            1    2    3   4
                                            5    6    7   8
                                            9    10  11 12
                                            13  14  15  16

The resultant array should be

1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16


#include<iostream.h>
#include<conio.h>

void main( )
{
int A[4][4], B[16];

// Input elements
for(int i = 0; i < 4 ; i++)
  for( int j = 0; j < 4 ; j++)
  {
  cout<<"\n Enter elements for "<< i+1 << "," << j+1   << "location :";
  cin >> A[i][j];
 }

clrscr();
//Print the array
cout<<"\n The Original matrix : \n\n";
for( i = 0; i < 4 ; i++)
{
 for( j = 0; j < 4 ; j++)
    cout<< A[i][j]<<"\t";
 cout<< "\n";
}

int k = 0;
// Convert 2 - D array into 1-D array by row-major rule
for( i = 0; i < 4 ; i++)
   for( j = 0; j < 4 ; j++)
    B[k] = A[i][j];

//display the 1D Array
for( k=0; k<16; k++)
cout<< B[k] << "  ";

getch( );
}

No comments:

Post a Comment

C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.
Now Playing: Ballade Pour Adeline

About Me

My photo
I m an IT lecturer of a college. I love social-work. I want to do something beneficial for society before dying , that can promote our society, to some extent.